0

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?

Hailong
  • 1,084
  • 10
  • 9
  • 3
    What does "elegant" even mean? — Why would you return if `a` is _not_ `nil`? Why would you force-unwrap `a` if it _is_ `nil`? Your code makes no sense. You would crash if you ran that code. – matt Jul 14 '16 at 04:46
  • My mistake, it should be equal. – Hailong Jul 14 '16 at 06:03

2 Answers2

5

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

guard let b = getFromSomewhere() else {return}
matt
  • 515,959
  • 87
  • 875
  • 1,141
3

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
Chajmz
  • 729
  • 5
  • 11