wigging
wigging

Reputation: 9170

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?

Upvotes: 0

Views: 182

Answers (3)

Code Different
Code Different

Reputation: 93151

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 }

Upvotes: 2

Luca Angeletti
Luca Angeletti

Reputation: 59496

As others already said, you are probably using temp outside of the scope of the if/else don't you?

This code will work

func foo(units:Int) -> String? {
    let result: String
    if units == 0 {
        guard let temp = currentDict["temp_f"] as? String else { return nil }
        result = temp
    } else {
        guard let temp = currentDict["temp_c"] as? String else { return nil }
        result = temp
    }
    return result
}

Upvotes: 1

Nathan Heskia
Nathan Heskia

Reputation: 17

Are you using the temp variable outside the if/else statement? That is most likely the source of your problem.

Upvotes: -1

Related Questions