0

Can someone help me understand the following code expression, how would you read it?

let myVar = (someOptional != nil) ? someOptional! : ""

If someOptional is not nil unwrap it? if this is correct, what does do the ? and the :"" in the expression?

I have always unwrapped my optionals with if lets but and I'm not sure how the above code reads.

Here is a more concrete real code example that shows how it is used...

let currentZipCode = (placemark.postalCode != nil) ? placemark.postalCode! : ""
fs_tigre
  • 10,650
  • 13
  • 73
  • 146
  • 3
    Look up “ternary conditional operator” in the Swift docs ... – Martin R Nov 22 '18 at 13:45
  • 3
    Also, this is poor usage of ternary operator, [`nil coalescing` operator](https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html) suits here better. – user28434'mstep Nov 22 '18 at 13:49
  • 2
    there is a quicker way to do this -> `let myVar = someOptional ?? ""` this means, if someOptional is not nil, use the unwrapped content but if it is nil, use "". --- just fyi – Sandu Nov 22 '18 at 13:50
  • Thank you all for the good information. I will read more about ternary conditional operator and coalescing operator. @user28434 - would you mind elaborating a little more on why it is a poor usage in this case? – fs_tigre Nov 22 '18 at 14:00
  • 1
    Using `nil coalescing operator` here is way more cleaner and shorter, less repetitions. Also, `??` operator will evaluate expression that is checked for `nil` only once, while that ad-hoc ternary operator will do it twice. If your `placemark.postalCode` causes some resource heavy calculations in the getter you will have them performed twice. – user28434'mstep Nov 22 '18 at 14:12
  • 1
    Also related: [When should I compare an optional value to nil?](https://stackoverflow.com/questions/29717210/when-should-i-compare-an-optional-value-to-nil) – Martin R Nov 22 '18 at 14:25

0 Answers0