Kelvin Lau
Kelvin Lau

Reputation: 6781

A better way to check dictionary for values

I am currently put in a project that has some beastly code snippet that checks particular values in a dictionary:

guard let userDictionary = Locksmith.loadDataForUserAccount("asdf"), _ = userDictionary["baseUrl"] as? String, _ = userDictionary["refreshToken"] as? String, _ = userDictionary["oauthCode"] as? String, _ = userDictionary["oauthKey"] as? String else { return false }
return true

Are there better ways to do this, such as using something like contains?

Upvotes: 1

Views: 66

Answers (1)

matt
matt

Reputation: 535989

If all you want to know is whether the dictionary contains a list of keys, you can test it like this:

Set(d.keys).isSupersetOf(["hey", "ho"])

But if you want to know, for each key, whether the corresponding value is of a certain type that is not the value type of the dictionary (i.e. it requires casting), then the way you are doing it is the only good way.

Upvotes: 3

Related Questions