3

What is the ?? operator

The Swift Programming Language (Swift 4.1)

I was reading the book The Swift Programming Language (Swift 4.1) by apple and I got to a part where it talks about the ?? operator:

Expert

Another way to handle optional values is to provide a default value using the ?? operator. If the optional value is missing, the default value is used instead.

Excerpt From: Apple Inc. “The Swift Programming Language (Swift 4.1).” iBooks. https://itunes.apple.com/us/book/the-swift-programming-language-swift-4-1/id881256329?mt=11

Problem

Optional Values

In the expert it says that the ?? operator is for a optional value I was wondering what it does for a Optional Value.

What it does

So the other thing I wanted to know is what does the ?? operator do.

Community
  • 1
  • 1
  • It's the [nil coalescing operator](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html#//apple_ref/doc/uid/TP40014097-CH6-ID72). – Hamish Apr 16 '18 at 17:02
  • That's what I mean what is the nil coalescing operator? –  Apr 16 '18 at 17:02
  • It means if the first value is nil, it returns the value of the second operand. – Daniel Gale Apr 16 '18 at 17:03
  • Oh that makes a lot more sense so the nil coalescing operator makes it so if you have to use a value (not nil) then it will assume the value of the nil coalescing value. –  Apr 16 '18 at 17:06

1 Answers1

0

Nil-Coalescing Operator (??)

The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

?? - indicates default value assignment, when your variable has a nil value.

Consider following example:

var int a = nil    // var a with nil value assignment

var int b = a ?? 1  // first trying to get value from a. If var a has nil then it will try assign value 1.

print("b = \(b)")

result: b = 1

Community
  • 1
  • 1
Krunal
  • 77,632
  • 48
  • 245
  • 261