Swift === with nil

前端 未结 2 606
心在旅途
心在旅途 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: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.

提交回复
热议问题