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?
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?
Omit a
, omit the nil check, omit the force-unwrap; one line:
guard let b = getFromSomewhere() else {return}
You can also use guard
or if let
to unwrap optionals:
so instead of :
if a != nil {
return
}
let b = a!
if let a = getFromSomewhere() {
// Do what you want with a
} else {
// a is nil
}
And with a guard statement :
guard let a = getFromSomewhere() else {
NSLog("error a is nil")
return
}
// You can use a now if it's not nil