'Comparing non-optional value of type 'Bool' to 'nil' always returns true

I have an if-else statement where I am checking if the value coming from user defaults is nil or not like this:

 if defaults.bool(forKey: "abcd") != nil{
       //Do something
    }
    else{
        //do something else
    }

But Xcode is giving me an error saying: "Comparing non-optional value of type 'Bool' to 'nil' always returns true"

Can someone explain what's happening here and how to fix this?



Solution 1:[1]

bool(forKey:) returns a NON-optional, which cannot be nil. If the key is missing in the user defaults, the return value will be false.

If you want trinary logic here (nil/true/false) use object(forKey:) looking for an NSNumber, and if present, take its boolValue.

Solution 2:[2]

As

defaults.bool(forKey: "abcd")

will return false by default check Docs , so it will never be optional

The Boolean value associated with the specified key. If the specified key doesn‘t exist, this method returns false.

Solution 3:[3]

The func bool(forKey: "abcd") returns Bool type not optional.

Which means you cant compare it to bool, what you can do is simply:

 if defaults.bool(forKey: "abcd") {
   //Do something
} else {
    //do something else
}

Now if the key exists and has true value it will get into the if statement, if it does not exists or is false it will go to the else.

If you have any doubts you can read about the func in the following Apple developer link: Apple:bool(forKey:)

Solution 4:[4]

Objective-c property in swift. If you're using some objective c property in swift and it says something like "Comparing non-optional value of type 'XYZ' to 'nil' always returns true" you have to make that objective c property to "_Nullable" so that property may not be optional anymore. Like @property (strong,nonatomic) NSString *_Nullable someString;

Solution 5:[5]

i have same problem and i solved like this:

if(Userdefaults.standart.bool(forkey: "blablabool"){

}

This works.. When you call this if its null it returns false.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rgeorge
Solution 2 Sh_Khan
Solution 3 Mr Spring
Solution 4 Meesum Naqvi
Solution 5