I'm iterating through a dictionary of [String: Any], looking for nils, so I can replace them with NSNull for a JSON write. My precompiler warning is telling me that comparing an Any to a nil will always be false, but I know it contains at least two nils which are never found. Is there a way to check is an Any is nil?
You can use if statement and compare optional with nil to find out whether a optional contains a value or not. You can use the comparison operator "equal to" operator ( == ) or the "not equal to" operator ( !=
Non-optional allows us to declare variables without optional and without initial value but we have to assign a value before using it other compile-time error. It can't be nil. *No default value. We can't assign nil to any non-optional variable. will get a compile-time error. During initialization.
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.)
if(object_getClass(yourVariable)?.description() == "NSNull")
can be one of the way to check.
I have solved this using bellow expression:
let filteredResult = dictionary.filter { !(($0.value as AnyObject) is NSNull) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With