Check if key exists in dictionary of type [Type:Type?]

Actually your test dictionary[key] == nil can be used to check
if a key exists in a dictionary. It will not yield true if the value
is set to nil:

let dict : [String : Int?] = ["a" : 1, "b" : nil]

dict["a"] == nil // false,     dict["a"] is .some(.some(1))
dict["b"] == nil // false !!,  dict["b"] is .some(.none)
dict["c"] == nil // true,      dict["c"] is .none

To distinguish between “key is not present in dict” and “value for key is nil” you
can do a nested optional assignment:

if let val = dict["key"] {
    if let x = val {
        print(x)
    } else {
        print("value is nil")
    }
} else {
    print("key is not present in dict")
}

Leave a Comment

tech