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?

Ky -
  • 30,724
  • 51
  • 192
  • 308
  • 1
    Oh, it's called "null coalescing"? Thanks! That's really helpful for Googling it. – Ky - Mar 25 '16 at 15:25
  • 1
    Named "nil coalescing operator" for Swift. :) https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html#//apple_ref/doc/uid/TP40014097-CH6-ID72 – Eric Aya Mar 25 '16 at 15:32

1 Answers1

14

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

let name = getName() ?? "backup";
Ky -
  • 30,724
  • 51
  • 192
  • 308