Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift optional binding with tuples

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")
}
like image 853
RMH Avatar asked Jan 16 '15 19:01

RMH


People also ask

What is optional binding in Swift?

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.

What does ~= mean in Swift?

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.

What is the difference between optional binding and optional chaining?

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.


1 Answers

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
}
like image 158
Airspeed Velocity Avatar answered Oct 12 '22 01:10

Airspeed Velocity