-1

I am trying to figure out how to properly use ?? in Swift.

I've seen it used in some classes but I am not sure why it's used and when it is appropriate to use.

Anybody has a good example that explains this?

zumzum
  • 15,369
  • 20
  • 94
  • 135
  • 1
    As [the documentation says](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html#//apple_ref/doc/uid/TP40014097-CH6-ID72), `a ?? b` is shorthand for `a != nil ? a : b`. That is, if `a` is not `nil`, then return `a`, but if it is `nil`, then return `b`. – Rob May 28 '15 at 23:24
  • @zumzum you should take a look also at the ternary conditional operator – Leo Dabus May 28 '15 at 23:25

3 Answers3

3

?? is a nil coalescing operator. It unwraps an Optional if a value exists, or uses a default value if the Optional is nil. For example:

let s1: String? = "my string"
let s2: String? = nil
let s3 = s1 ?? "no value"  // s3 = "my string"
let s4 = s2 ?? "no value"  // s4 = "no value"
mipadi
  • 380,288
  • 84
  • 512
  • 473
2

?? is the “nil-coalescing” operator.

Optionals – containing types that might, or might not, contain a value – are fundamental to Swift code.

For example, the String method toInt() returns an optional Int, that is, an Int?. If the string is not a valid number, it returns nil. If it is, the optional will “wrap” the actual number:

"1".toInt()    // returns {Some 1}
"foo".toInt()  // returns nil

The ?? operator is a way to replace nil with a default, and if it isn’t nil, unwrap it. So:

// if s isn’t a valid integer, default to 0
let i = "1".toInt() ?? 0   // i will be 1 (not {Some 1})
let j = "foo".toInt() ?? 0 // j will be 0

An imperfect analogy is that x ?? y is equivalent to x != nil ? x! : y.

But there are a handful of ways in which it differs – for example, you can chain it:

"foo".toInt() ?? "bar".toInt() ?? 0

You can read more about optionals here and unwrap techniques here

Community
  • 1
  • 1
Airspeed Velocity
  • 39,686
  • 7
  • 107
  • 114
  • I marked this as the best answer because it also shows the chaining use of it which I could not find on on other answers in stack overflow. Thanks – zumzum May 30 '15 at 08:18
0

The question marks after a type refer to Optionals, this is a mechanism in Swift which lets you indicate that a value might be absent for any type.

To unwrap an optional you can use the Nil Coalescing Operator (??) which allows setting either the unwrapped value or an alternative value in the case that the optional value is nil.

optionalValue ?? valueIfNil
JosEduSol
  • 5,088
  • 3
  • 21
  • 31
  • but why two question marks in a row? I have used the ? operator a lot, but I don't see when it is appropriate to use two? – zumzum May 28 '15 at 22:58