简体   繁体   中英

Swift comparing Strings optionals vs non-optional

When comparing strings in Swift, you can compare non-optional strings with optional strings.

Like so (text is an optional, and it is empty):

UITextField.text == "" // True

Is it because the equality operator unwraps Strings by itself?

For every Equatable type the == operation is also defined for optionals:

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

The non-optional on the right side gets automatically promoted to an optional.

The == for optionals returns true when both values are nil or if they are both non-nil and they are equal.

Your theory doesn't hold in the following example:

let x: String? = nil

if x == "" {
    print("True")
} else {
    print("False") //Printed
}

What's actually happening here is that the text property is never actually nil upon initialisation — it is instead an empty string, as given by the documentation :

This string is @"" by default.

The Swift compiler does not implicitly unwrap any optionals, it instead leaves that responsibility to the programmer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM