Tang
Tang

Reputation: 401

How to check dictionary contains certain value, not certain key?

Fast way to check if dictionary contains certain value, like "dictionary.contains(value)" in Java. Ex:

var dict:[Int:String?] = [1:"hello", 2:"world"]

How can I check if the dictionary contains "world"?

Upvotes: 1

Views: 1029

Answers (1)

zneak
zneak

Reputation: 138251

Your only option is to iterate on each dictionary element to find if that value is present. There are multiple ways to do that, but they are all linear-time.

One such way would be:

foreach (key, value) in dict {
    if value == "world" {
        print("Found world")
    }
}

Another (shorter) way would be:

dict.values.contains("world")

Upvotes: 3

Related Questions