Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpredictable nil check result

Unpredictable (unobvious) nil check:

this function:

fileprivate func isPurchased(_ name: String) -> Bool {
        if let _ = dictionary[name] {
            return true
        } else {
            return false
        }
    }

returns true for:

fileprivate var dictionary = [String: Double?]()

and false for [String: Double] (that's normal). Why?

I initialize dictionary like this:

dictionary["test"] = nil

I mean:

isPurchased("test") returns true for [String: Double?]

and

isPurchased("test") returns false for [String: Double]

UPDATE

 var dictionary = [String: Double?]()
dictionary["test"] = nil
print("\(isPurchased("test"))") 

prints true

 var dictionary = [String: Double]()
dictionary["test"] = nil
print("\(isPurchased("test"))") 

prints false

why?

like image 471
Vyacheslav Avatar asked Jan 21 '26 05:01

Vyacheslav


1 Answers

First, don't use if let to check if something's nil. Just use value == nil

As discussed in the comments, getting the value with the subscript from a dictionary of type [String: Double?] results in a double-optional (Double??).

This means dictionary[name] has a value of Optional.some(Optional.none).

To get around this, you can do something like:

if let value = dictionary["test"], value != nil 
like image 146
GetSwifty Avatar answered Jan 23 '26 20:01

GetSwifty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!