I'm trying to use a tuple as an optional binding in an IF statement in Swift but it won't compile and that error message is less than helpful. Why doesn't the following compile?
let user:String? = "billy"
let pass:String? = "password"
if let test = (user?,pass?){
print("this works")
}
or this
let user:String? = "billy"
let pass:String? = "password"
if let test = (user,pass){
print("this works")
}
Optional binding is a mechanism built into Swift to safely unwrap optionals. Since an optional may or may not contain a value, optional binding always has to be conditional. To enable this, conditional statements in Swift support optional binding, which checks if a wrapped value actually exists.
The expression represented by the expression pattern is compared with the value of an input expression using the Swift standard library ~= operator. The matches succeeds if the ~= operator returns true . By default, the ~= operator compares two values of the same type using the == operator.
Difference between Optional Chaining and Optional Binding: 1. Optional binding stores the value that you're binding in a variable. 2. Optional chaining doesn't allows an entire block of logic to happen the same way every time.
edit: as of Swift 1.2 in Xcode 6.3, you can now do:
if let user = user, pass = pass { }
to bind multiple unwrapped optional values.
You can't use optional let binding that way. let test = (user,pass)
won't compile since (user,pass)
is not an optional – it's a tuple that contains optionals. That is, it's an (Int?,Int?)
not an (Int,Int)?
.
This should do what you want and allows you to bind two items simultaneously:
switch (user, pass) {
case let (.Some(user), .Some(pass)):
print("this works: \(user), \(pass)")
default: () // must handle all cases
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With