Swift comparing Strings optionals vs non-optional

后端 未结 2 1974
旧时难觅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: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.

提交回复
热议问题