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?
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?
?? 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"
?? 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
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