Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 322
i_am_jorf Avatar asked Sep 26 '16 19:09

i_am_jorf


2 Answers

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

like image 50
Rob Napier Avatar answered Oct 14 '22 01:10

Rob Napier


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 { 
  ...
}
like image 27
Rashwan L Avatar answered Oct 14 '22 03:10

Rashwan L