Simplify guard initialization for multiple variables

Direct to the point, I would like suggest the guard statement for initializing multiple assignments.

Current Syntax
guard let val1 = Int("1"), let val2 = Int("2"), let val3 = Int("3") else { return }
Proposed Syntax
guard let val1 = Int("1"), val2 = Int("2"), val3 = Int("3") else { return }

This reduces repetitive let or var keyword for every variable/constant we initialize in guard. I believe the new syntax doesn't introduce any confusion to developers.

Hey, this was actually explicitly removed by SE-0099 Restructuring Condition Clauses.

7 Likes

Just use this syntax instead

guard let (val1, val2, val3) = (Int("1"), Int("2"), Int("3")) else { 
       return 
}

Initializer for conditional binding must have Optional type, not '(Int?, Int?, Int?)'

I think you need to use guard case let.

Thanks for the correction

// warning: 'guard' condition is always true, body is unreachable
guard case let (val1, val2, val3) = (Int("1"), Int("2"), Int("3")) else {
  return
}
// val1: Int? = 1
// val2: Int? = 2
// val3: Int? = 3

You also need to use ? patterns:

// OK
guard case let (val1?, val2?, val3?) = (Int("1"), Int("2"), Int("3")) else {
  return
}
// val1: Int = 1
// val2: Int = 2
// val3: Int = 3
1 Like
Terms of Service

Privacy Policy

Cookie Policy