Stanislav Smida Stanislav Smida - 1 year ago 81
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>

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download