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
The problem is merely one of inferred type. Don't let Swift infer the type here. Write this:
let result : Int = optional ?? defaultValue
Now you'll get the result you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With