i_am_jorf i_am_jorf - 2 months ago 9
Swift Question

Are multiple lets in a guard statement the same as a single let?

Is there any functional difference between:

guard let foo = bar, let qux = taco else {
...
}


And:

guard let foo = bar, qux = taco else {
...
}


It seems to me they're the same and the extra
let
is not required?

Answer

These are different in Swift 3. In this case:

guard let foo = bar, let qux = taco else { 

you're saying "optional-unwrap bar into foo. If successful, optional unwrap taco into qux. If successful continue. Else ..."

On the other hand this:

guard let foo = bar, qux = taco else {

says "optional-unwrap bar into foo. As a Boolean, evaluate the assignement statement qux = taco" Since assignment statements do not return Booleans in Swift, this is a syntax error.

This change allows much more flexible guard statements, since you can intermix optional unwrapping and Booleans throughout the chain. In Swift 2.2 you had to unwrap everything and then do all Boolean checks at the end in the where clause (which sometimes made it impossible to express the condition).