wigging wigging - 6 months ago 19
Swift Question

Guard in a conditional statement

Depending on the value of the

units
parameter, I would like to unwrap the Fahrenheit or Celsius temperature using
guard
. However, I get an error about


Use of unresolved identifier 'temp'


from the following example code

let units = 0

if units == 0 {
guard let temp = currentDict["temp_f"] as? String else { return nil }
} else {
guard let temp = currentDict["temp_c"] as? String else { return nil }
}


Why does
guard
not work in this example?

Answer

It doesn't work because temp was scoped to be within the if statement only. Try this instead:

let key = units == 0 ? "temp_f" : "temp_c"
guard let temp = currentDict[key] as? String else { return nil }