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):
@warn_unused_result
public func ??<T>(optional: T?, @autoclosure defaultValue: () throws -> T?) rethrows -> T?
@warn_unused_result
public func ??<T>(optional: T?, @autoclosure defaultValue: () throws -> T) rethrows -> T
let val1: Int? = nil
let val2 = 1
let val3 = val1 ?? val2 // 1
val3.dynamicType // Int.Type
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments