i_am_jorf
i_am_jorf

Reputation: 54600

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?

Upvotes: 10

Views: 8569

Answers (2)

Rob Napier
Rob Napier

Reputation: 299275

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).

Upvotes: 19

Rashwan L
Rashwan L

Reputation: 38833

No it´s not the same anymore in Swift 3.0. Xcode gives you an error and asks you to add let when you´re applying multiple variables.

enter image description here

So you should use

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

Upvotes: 7

Related Questions