4thSpace
4thSpace

Reputation: 44310

Why doesn't guard create unwrapped var?

Why do I need to unwrap the variable unwrapped in the final return statement? Isn't guard supposed to handle this?

func test() -> String {
    let fmt = NSNumberFormatter()
    let myValue:Double? = 9.50
    guard let unwrapped = myValue else {
        return ""
    }
    return fmt.stringFromNumber(unwrapped)
}

error: value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'? return fmt.stringFromNumber(unwrapped)

Upvotes: 2

Views: 86

Answers (1)

Code Different
Code Different

Reputation: 93151

It's not the variable unwrapped. It's stringFromNumber: it returns an optional string. But your function returns a string, hence you must unwrap:

return fmt.stringFromNumber(unwrapped)!

There's a difference between these 2:

return fmt.stringFromNumber(unwrapped!)
return fmt.stringFromNumber(unwrapped)!

Upvotes: 8

Related Questions