4thSpace
4thSpace

Reputation: 44352

How to access dictionary key via index?

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.

Upvotes: 4

Views: 1101

Answers (2)

turushan
turushan

Reputation: 720

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.

Upvotes: 0

Eric Aya
Eric Aya

Reputation: 70118

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.

Upvotes: 2

Related Questions