How to get the key to a specific index from a dictionary in Swift?

I have a Dictionary in Swift, and I would like to get the key at a specific index.

 var myDict : Dictionary<String,MyClass> = Dictionary<String,MyClass>() 

I know that I can iterate over keys and write them down

 for key in myDict.keys{ NSLog("key = \(key)") } 

However, oddly enough, something like this is impossible

 var key : String = myDict.keys[0] 

Why?

+85
dictionary ios swift
Jul 08 '14 at 20:15
source share
11 answers

This is because keys returns LazyMapCollection<[Key : Value], Key> , which cannot be indexed using Int. One way to handle this is to promote the startIndex dictionary startIndex an integer that you would like to index, for example:

 let intIndex = 1 // where intIndex < myDictionary.count let index = myDictionary.startIndex.advancedBy(intIndex) // index 1 myDictionary.keys[index] 

Another possible solution would be to initialize the array with keys as input, then you can use integer indices for the result:

 let firstKey = Array(myDictionary.keys)[0] // or .first 

Remember, dictionaries are inherently disordered, so do not expect that the key in this index will always be the same.

+156
Jul 08 '14 at 20:20
source share

Swift 3: Array() may be useful for this.

Get the key:

 let index = 5 // Int Value Array(myDict)[index].key 

Get value:

 Array(myDict)[index].value 
+35
May 10 '17 at 10:06
source share

Here is a small extension for accessing keys and values ​​in a dictionary by index:

 extension Dictionary { subscript(i: Int) -> (key: Key, value: Value) { return self[startIndex.advancedBy(i)] } } 
+19
Jul 29 '15 at 0:12
source share

You can iterate through a dictionary and grab an index with input and enumeration (as others have said, there is no guarantee that it will exit as shown below)

 let dict = ["c": 123, "d": 045, "a": 456] for (index, entry) in enumerate(dict) { println(index) // 0 1 2 println(entry) // (d, 45) (c, 123) (a, 456) } 

If you want to sort first ..

 var sortedKeysArray = sorted(dict) { $0.0 < $1.0 } println(sortedKeysArray) // [(a, 456), (c, 123), (d, 45)] var sortedValuesArray = sorted(dict) { $0.1 < $1.1 } println(sortedValuesArray) // [(d, 45), (c, 123), (a, 456)] 

then iteration.

 for (index, entry) in enumerate(sortedKeysArray) { println(index) // 0 1 2 println(entry.0) // acd println(entry.1) // 456 123 45 } 

If you want to create an ordered dictionary, you should look at Generics.

+11
Mar 31 '15 at 2:25
source share

From https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/CollectionTypes.html :

If you need to use keys or dictionary values ​​with an API that accepts an Array instance, initialize a new array using the properties of the keys or values:

 let airportCodes = [String](airports.keys) // airportCodes is ["TYO", "LHR"] let airportNames = [String](airports.values) // airportNames is ["Tokyo", "London Heathrow"] 
+8
Jul 08 '14 at 20:21
source share

SWIFT 3. Example for the first element

 let wordByLanguage = ["English": 5, "Spanish": 4, "Polish": 3, "Arabic": 2] if let firstLang = wordByLanguage.first?.key { print(firstLang) // English } 
+4
Dec 21 '16 at 15:18
source share

In Swift 3, try using this code to get a pair of key (tuple) values ​​at a given index:

 extension Dictionary { subscript(i:Int) -> (key:Key,value:Value) { get { return self[index(startIndex, offsetBy: i)]; } } } 
+4
Jun 21 '17 at 9:17
source share

Here is an example using Swift 1.2

 var person = ["name":"Sean", "gender":"male"] person.keys.array[1] // "gender", get a dictionary key at specific index person.values.array[1] // "male", get a dictionary value at specific index 
+3
Aug 31 '15 at 8:05
source share

SWIFT 4




A little off topic: but if you have an array of dictionaries, that is: [[String: String]]

 var array_has_dictionary = [ // Start of array // Dictionary 1 [ "name" : "xxxx", "age" : "xxxx", "last_name":"xxx" ], // Dictionary 2 [ "name" : "yyy", "age" : "yyy", "last_name":"yyy" ], ] // end of array cell.textLabel?.text = Array(array_has_dictionary[1])[1].key // Output: age -> yyy 
+1
Aug 04 '17 at 0:03
source share

In SWIFT 4, you can do what you want:

 let dic = [1 : "First", 2 : "Second", 3 : "third"] for key in dic.keys { print(key) } 
0
Aug 20 '17 at 8:54 on
source share

I was looking for something like LinkedHashMap in Java. Neither Swift nor Objective-C have this, if I'm not mistaken.

My initial thought was to wrap my dictionary in an array. [[String: UIImage]] but then I realized that the key capture from the dictionary is stupid with Array(dict)[index].key so I went with Tuples. Now my array looks like [(String, UIImage)] so I can get it with tuple.0 . You no longer need to convert it to an array. Just my 2 cents.

0
Mar 15 '18 at 20:49
source share



All Articles