Comparing non-optional Any to nil is always false?

前端 未结 2 1470
太阳男子
太阳男子 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.)

    0 讨论(0)
  • 2021-01-18 13:35

    if(object_getClass(yourVariable)?.description() == "NSNull") can be one of the way to check.

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