Hailong Hailong - 1 year ago 90
Swift Question

Best way to unwrap optional type

I have a situation

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

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

Answer Source

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

guard let b = getFromSomewhere() else {return}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download