Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift operators and nil [duplicate]

Tags:

swift

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?

EDIT:

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.

like image 621
Darko Avatar asked Oct 19 '15 13:10

Darko


1 Answers

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) { ... }

Update:

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).

like image 69
Martin R Avatar answered Oct 14 '22 00:10

Martin R