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

2

10

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?

Nicholnichola answered 26/9, 2016 at 19:1 Comment(1)
The second variant was allowed in Swift 2, but isn't anymore in Swift 3.Pogrom
E
19

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

Ectoderm answered 26/9, 2016 at 19:27 Comment(2)
Okay, good to know. Obviously I'm still on swift 2. I have a linter that is complaining about the first syntax that is going to need some changing when we upgrade. Thanks!Nicholnichola
Xcode 8 itself will periodically display an error for this if you're working with Swift 2.3, then it goes away on some final pass the compiler makes.Submarginal
U
7

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 { 
  ...
}
Untruthful answered 26/9, 2016 at 19:4 Comment(1)
same in Swift 4 too, must need a 'let' for every guard check !Brotherton

© 2022 - 2024 — McMap. All rights reserved.