I am doing this to loop through my dictionary until until I match the key. My dictionary is defined as [Int:String]
var index = 0
for (key, value) in mylist! {
if key == property.propertyValue as! Int {
// use index here
}
index += 1
}
Is there a better way to do this? I see examples of filtering (something like the example below) but I am not sure how to make it work with a dictionary. Could I use something like this to find the index of the item? Or is there another way?
mylist.filter{$0.key == 1}
UPDATE: This works:
let index = Array(mylist!.keys).index(of: 1)
But this doesn't:
let index = mylist!.index(forKey: 1)
It seems they both should work. I wonder why the 2nd one doesn't.
A dictionary is an unordered collection type and doesn't have an index.
You can get the value directly by the key
let value = mylist[property.propertyValue as! Int]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With