Hailong Hailong - 4 months ago 10
Swift Question

Best way to unwrap optional type

I have a situation

let a: Int? = getFromSomewhere()
if a == nil {
return
}
let b = a!


I don't like too many layer. But I think this is not elegant.
Do you have more elegant way?

Answer

Omit a, omit the nil check, omit the force-unwrap; one line:

guard let b = getFromSomewhere() else {return}
Comments