Sahil
Sahil

Reputation: 9226

Satisfy one of multiple constraints in an if let construct

I want to satisfy multiple constraints in an if let construct. I know we can use a "," (comma) to unwrap multiple values but they both have to be successfully unwrapped.

For example :

var str: String? = "Hello"
var x: Int? = 10

if let intValue = x, stringValue = str {
// do something here. 

} else {

}

I want if one of the conditions is successfully unwrapped, then a block will execute. for example:

class CustomClass {
 var x = 10

 static func someValue() -> String? {
 return "some"
 }
}

  var flag: Bool? = false
  var x: Int? = 10
  var status: String

in this i want if either customclass someValue function or x value any of successfully unwrapped and flag is true then code executes

Upvotes: 1

Views: 89

Answers (1)

beyowulf
beyowulf

Reputation: 15331

You can create a tuple and use a switch like so:

switch (str, x) {
case (.Some,.Some):
    print("Both have values")
case (.Some, nil):
    print("String has a value")
case (nil, .Some):
    print("Int has a value")
case (nil, nil):
    print("Neither has a value")
}

Upvotes: 5

Related Questions