Darko Darko - 11 months ago 48
Swift Question

Swift operators and nil

What is the explanation for this behavior?

let x: Int? = nil
if x < 10 {
print("x < 10")

It prints "x < 10". Shouldn't this produce a runtime error or at least a compiler warning?


I submitted a bug report to Apple and they acknowledged it as an already existing duplicate of another report. So this will be handled/fixed by Apple in some way.

Answer Source

Two things happen here (whether we like it or not): First, there is an operator

public func <<T : Comparable>(lhs: T?, rhs: T?) -> Bool

which compares two optionals if the underlying type is comparable. The behavior is not documented (as far as I know), but it seems that nil aka Optional<T>.None is considered less than all non-nil values Optional<T>.Some(value).

Second, enum Optional has a constructor

/// Construct a non-`nil` instance that stores `some`.
public init(_ some: Wrapped)

Now in

if x < 10 { ... }

the lhs has the type Optional<Int>. The only candidate for the < operator is the above-mentioned one comparing two optionals. Therefore the rhs is inferred as an optional as well, so this is equivalent to

if x < Optional<Int>.Some(10) { ... }


This feature has been removed in Swift 3 (SE-0121 – Remove Optional Comparison Operators) and that code no longer compiles with Xcode 8 (currently beta 6).