Reputation: 1133
I have a quick question about how to loop through a dictionary key and compare its key to my integer, then print out the corresponding value if the key exists.
For example, this is my code
for(var j = 0; j <= someDictionary.count; j++) {
if ( someInteger == someDictionary.keys[j] ) {
someDictioanrysValue = someDictionary.values[j]
println(someDictioanrysValue)
}
}
is there a method in dictionary that does what I want already?
Upvotes: 0
Views: 596
Reputation: 22969
If I understand what you're trying to do correctly, you're just looking to use the subscript - no for
loops required.
let dict = [1: "A", 3: "B", 5: "C"]
let myInt = 3
if let value = dict[myInt] {
print(value)
}
// Prints: B
If a value doesn't exist for the key you supplied, nil
will be returned and so the code inside the if let
won't be executed.
If you're unfamiliar with this I'd really recommend you take a look at The Swift Programming Language.
Upvotes: 1