iOS Dev Nugget 207 Swift Nil-Coalescing Operator


Need to run a code review on your codebase? Hire me

In #61, I talked about the null coalescing operator for Obj-C. This is also available in Swift as the nil-coalescing operator ??.

Here's an example where it's useful. You have an optional object that you want to use if it contains a value, otherwise fallback to a default.

let possiblyNilObject: NSObject? = nil
let defaultObject = NSObject()

You could use if-let-else:

let v3: NSObject
if let v1 = possiblyNilObject {
    v3 = v1
} else {
    v3 = defaultObject

Or the ternary conditional operator:

let v4 = possiblyNilObject != nil ? possiblyNilObject! : defaultObject

Or alternatively, the nil-coalescing operator:

let v5 = possiblyNilObject ?? defaultObject

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No



Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter


View archives of past issues