Stanislav Smida Stanislav Smida - 6 months ago 8
Swift Question

Why does the nil coalescing operator wrap an implicitly unwrapped default value?

I see there is no reason that operator returns implicitly unwrapped optional. But what is the point that it wraps an implicitly unwrapped optional default value into optional (wrapped)? I just would expect non-optional result. Am I thinking somehow wrong here?

var defaultValue: Int! = 0
var optional: Int?

let result = optional ?? defaultValue

print(defaultValue.dynamicType) // ImplicitlyUnwrappedOptional<Int>
print(result.dynamicType) // Optional<Int>


Look in the Swift module where the nil coalescing operator is declared. ?? explicitly returns an optional if the second operand is a non-optional (if you let Swift infer the type):

public func ??<T>(optional: T?, @autoclosure defaultValue: () throws -> T?) rethrows -> T?

public func ??<T>(optional: T?, @autoclosure defaultValue: () throws -> T) rethrows -> T

If both types are non-optionals, ?? will return a non-optional:

let val1 = 1
let val2 = 2

let val3 = val1 ?? val2 // 1

val3.dynamicType // Int.Type