Swift === with nil

前端 未结 2 607
心在旅途
心在旅途 2021-02-13 04:00

Why does the following not work in Swift?

if someObject === nil {
}

You have to do the test using the == operator such as

if someO         


        
相关标签:
2条回答
  • 2021-02-13 04:46

    My first instinct would be that nil is not a class instance, but a reference. So someObject cannot be an equivalent class instance to nil.

    0 讨论(0)
  • 2021-02-13 04:53

    It works exactly like you expect:

    var s: String? = nil
    s === nil // true
    

    The only caveat is that to compare to nil, your variable must able to be nil. This means that it must be an optional, denoted with a ?.

    var s: String is not allowed to be nil, so would therefore always returns false when === compared to nil.

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