Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use ?: in Swift? [duplicate]

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?

like image 953
Ky. Avatar asked Mar 25 '16 15:03

Ky.


1 Answers

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

let name = getName() ?? "backup";
like image 73
Ky. Avatar answered Sep 20 '22 23:09

Ky.