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?
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
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