Comparison with Optional Values in Swift

Comparison with Optional Values in Swift


How it works...


An Optional is handled differently in an equality comparison with a value that’s not nil.

In such an operation, the wrapped value rather than the Optional itself is compared.



var hello: String? = "hello world"

if hello == "hello world" {
    print("\(hello) is hello world")
}

// output: Optional("hello world") is hello world
        

In this code, the variable hello references an Optional String that wraps the String “hello world.


Next, the Optional String (hello) is compared to the String “hello world” and the result is true because the text inside the if-block is printed.


Essentially, what’s happening here is that an Optional String is being compared to a normal String and the comparison automagically succeeds.


Considering that these are two different types, the compiler should throw an error, but it doesn’t and here's why:

  1. Swift is comparing the wrapped value (the String “hello world”) and not the Optional itself.
  2. If the wrapped value is nil the comparison safely fails.
  3. The operation depends on the wrapped type adopting the Equatable protocol — meaning it’s useable with ==.


Greater-Than and Less-Than Operators


var hello: String? = "hello world"

if hello < "hello world" {
    print("\(hello) is less than String hello world") // Error: Value of optional type 'String?' must be unwrapped to a value of type 'String'
} else {
    print("\(hello) is not less than String hello world")
}
        

Here, we’re using the less-than-operator and it results in the following compile error:


// Value of optional type 'String?' must be unwrapped to a value of type 'String'        

This happens because direct comparisons of Optionals using inequality comparison (greater-than or lesser-than) require that you first unwrap the Optional.



var hello: String? = "hello world"

if hello! < "hello world" {
    print("\(hello) is less than String hello world")
} else {
    print("\(hello) is not less than String hello world")
}

// output: Optional("hello world") is not less than String hello world        

By unwrapping the Optional the comparison can be applied directly to the unwrapped value.

要查看或添加评论,请登录