0

the question that I want to ask, from which directions swift starts to read dictionaries or arrays

when I put some codes like this

let interestingNumber = [
    "Square": [1,4,9,16,25],
    "Prime": [2,3,5,7,11,13],
    "Fiboannci": [1,1,2,3,5,8],
    "asd":[2,3,4,5],
    "zxc":[3,4,5]
]

for (key,values) in interestingNumber{
    print(values)
}

the output is

[1, 4, 9, 16, 25]
[2, 3, 5, 7, 11, 13]
[1, 1, 2, 3, 5, 8]
[3, 4, 5]
[2, 3, 4, 5]

this is not the exact order, so do you know why swift does this ? and it sometimes makes it different too!

I guessed may be it does it in string order, then I tried but I think it is not too, so why swift does do that ?

Hamish
  • 78,605
  • 19
  • 187
  • 280
Ozan Honamlioglu
  • 765
  • 1
  • 8
  • 20
  • 1
    The order of a dictionary's key-value pairs is unspecified and completely implementation dependant. You should not rely on it. – Hamish Feb 28 '17 at 13:50
  • Dictionary stored the key value with no defined order.. http://stackoverflow.com/questions/29601394/swift-stored-values-order-is-completely-changed-in-dictionary – Salman Ghumsani Feb 28 '17 at 13:54

1 Answers1

1

Just like for NSDictionary, Swift dictionaries are not ordered by key or value. The order will always be unspecified. If you need the keys to be sorted, your only option is to have an array of ordered keys, and use the for loop over this array.

From apple documentation (https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105)

Dictionaries

A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order. You use a dictionary when you need to look up values based on their identifier, in much the same way that a real-world dictionary is used to look up the definition for a particular word.

Giuseppe Lanza
  • 3,519
  • 1
  • 18
  • 40