4

Is there a way to access dictionary keys in Swift 2 using an index?

var dict = ["item1":1, "item2":2, "item3":3]
dict.keys[0]

results in the error:

15:29: note: overloads for 'subscript' exist with these partially matching parameter lists: (Base.Index), (Range), (Self.Index) print("key=" + dict.keys[i])

I saw an examples from August (Swift: dictionary access via index) doing this:

dict.keys.array[0]

At least in Swift 2, there isn't an array object on dictionary keys.

Community
  • 1
  • 1
4thSpace
  • 43,672
  • 97
  • 296
  • 475

2 Answers2

2

In Swift 2 the equivalent of dict.keys.array would be Array(dict.keys):

let dict = ["item1":1, "item2":2, "item3":3]

let firstKey = Array(dict.keys)[0]  // "item3"

Note: of course, as dictionaries are unordered collections, "first key" of the resulting array may not have a predictable value.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
0

do not rely on order of items in a dictonary, using array directly would be better in your case, you can also handle key/value in array with making array units objects.

turushan
  • 690
  • 7
  • 25