Swift comparing Strings optionals vs non-optional

后端 未结 2 1950
旧时难觅i
旧时难觅i 2021-01-13 10:41

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

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

UITextF         


        
相关标签:
2条回答
  • 2021-01-13 10:42

    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.

    0 讨论(0)
  • 2021-01-13 10:51

    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.

    0 讨论(0)
提交回复
热议问题