How do I use ?: in Swift? [duplicate]
Asked Answered
G

1

7

I love this syntax in Objective-C, where a question mark and colon let you use a backup value:

NSString const name = [self getName] ?: @"backup";

and I want to use the same in Swift, but I get this when I try:

<code>let name = getName() ?: "backup";</code> results in errors where the compiler completely doesn't recognize the syntax

Is there any way to do this in Swift? If not, can I write a custom infix operator to do it?

Geronto answered 25/3, 2016 at 15:20 Comment(2)
Oh, it's called "null coalescing"? Thanks! That's really helpful for Googling it.Geronto
Named "nil coalescing operator" for Swift. :) developer.apple.com/library/ios/documentation/Swift/Conceptual/…Moxie
G
14

It's called a null (or nil) coalescing operator, and the Swift syntax is:

let name = getName() ?? "backup";
Geronto answered 25/3, 2016 at 15:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.