Swift optional variable assignment with ??

Old way:

let foo = "Hello"
var bar = String? //nil
var result = (bar != nil) ? bar! : foo
print("\(result)") //Hello

Pretty nifty. I saw this online someplace. The ?? is called a nil coalescing operator. It’s used to provide a default value when unwrapping an optional type.

let foo = "Hello"
var bar = String? //nil
var result = bar ?? foo 
print("\(result)") //Hello

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.