Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing non-optional Any to nil is always false?

Tags:

swift

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?

like image 534
mcornell Avatar asked Nov 18 '16 20:11

mcornell


People also ask

How do you know if optional 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 ( !=

What is non optional in Swift?

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.


3 Answers

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.)

like image 167
matt Avatar answered Oct 04 '22 19:10

matt


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

like image 33
Venu Gopal Tewari Avatar answered Oct 04 '22 19:10

Venu Gopal Tewari


I have solved this using bellow expression:

let filteredResult = dictionary.filter { !(($0.value as AnyObject) is NSNull) }
like image 27
user3094614 Avatar answered Oct 04 '22 20:10

user3094614