Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of item in dictionary by key in Swift

Tags:

swift

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.

like image 964
Primico Avatar asked Jan 31 '23 03:01

Primico


1 Answers

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]
like image 109
vadian Avatar answered Feb 01 '23 16:02

vadian