Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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>
like image 479
Stanislav Smida Avatar asked Nov 16 '25 12:11

Stanislav Smida


2 Answers

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
like image 79
JAL Avatar answered Nov 19 '25 00:11

JAL


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.

like image 40
matt Avatar answered Nov 19 '25 00:11

matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!