SLN SLN - 1 year ago 57
Swift Question

It does not trigger any errors when apply the Nil-Coalescing operator on a none optional variable

The nil-coalescing operator (a ?? b) unwraps an optianl a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type.

The Nil-Coalescing operator is shorthand for the code below

a != nil ? a! : b

I've then tried the following test code snippet

let a: Int = 3, b: Int = 4
a ?? b // No error


let a: Int = 3, b: Int = 4
a != nil ? a! : b //Triggers an error: value of type 'int' can never be nil, comparison isn't allowed

Question :

Why the Compiler didn't give an error for the first code snippet while yelling an error for the second one? Ain't they are same?

Many Thanks

enter image description here

enter image description here

Answer Source

The nil-coalescing operator

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

takes an optional a the first operand. So a ?? b and a != nil ? a! : b are equivalent provided that a is an optional.

That is not the case in your example

let a: Int = 3, b: Int = 4
a ?? b

The first operand a is not an optional. However, the compiler can "wrap" a non-optional value T into an optional T? in order to match a function or operator. For example, in

func foo(x: Int?) { }

the argument 3 is wrapped into an Int?.

In your case, the expression is equivalent to

Optional<Int>.Some(a) ?? b

which is equivalent to

Optional<Int>.Some(a) != nil ? Optional<Int>.Some(a)! : b

However, the compiler is not so smart to recognize that Optional<Int>.Some(a) cannot be nil.