Comparing non-optional Any to nil is always false?

前端 未结 2 1516
太阳男子
太阳男子 2021-01-18 12:54

I\'m iterating through a dictionary of [String: Any], looking for nils, so I can replace them with NSNull for a JSON write. My precomp

2条回答
  •  没有蜡笔的小新
    2021-01-18 13:13

    An Optional can be nil. Anything else can never be nil. An Any is not an Optional. Thus there is no point comparing an Any to nil. The test will never succeed.

    If you know that these things might be Optionals, you should have typed this as Any?. That is an Optional and can be compared to nil. Here's a simple example:

        let s : String? = nil
        let any : Any? = s
        if any == nil {
            print("nil") // nil
        }
    

    As you can see, the test succeeds.

    (Still, if at all possible, it would be even better to type things more precisely.)

提交回复
热议问题