Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

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

How can I check if a key exists in a dictionary? My dictionary is of type [Type:Type?].

I can't simply check dictionary[key] == nil, as that could result from the value being nil.

Any ideas?

question from:https://stackoverflow.com/questions/29299727/check-if-key-exists-in-dictionary-of-type-typetype

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 {
        println(x)
    } else {
        println("value is nil")
    }
} else {
    println("key is not present in dict")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...