5

Hello I tried a print dictionary items at Xcode9. Like this:

var items = ["Bear":"0", "Glass":"1", "Car":"2"]

for (key,value) in items{

print("\(key) : \(value)")

}

output:

Glass : 1
Bear : 0
Car : 2

Why output not like this: Bear: 0, Glass:1, Car:2 I dont understand this output reason.

Hamish
  • 78,605
  • 19
  • 187
  • 280
Mayday
  • 121
  • 1
  • 3
  • 9

4 Answers4

11

Dictionary :

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.

Array - An array stores values of the same type in an ordered list.

Sets - A set stores distinct values of the same type in a collection with no defined ordering.

From Apple documentation

enter image description here

Dharma
  • 3,007
  • 3
  • 23
  • 38
3

Dictionary in Swift is implemented as hash map. There is no guarantee that items in Dictionary will have the same order you added them.

The only container that retains the order of items is Array. You can use it to store tuples, like so:

var items : [(key: String, value: String)] = [(key: "Bear", value: "0"),(key: "Glass", value: "1"), (key: "Car", value: "2")]

Your iteration will work as expected, but you will lose Dictionary's ability to lookup items by subscript

rmaddy
  • 314,917
  • 42
  • 532
  • 579
mag_zbc
  • 6,801
  • 14
  • 40
  • 62
1
  • Arrays are ordered collections of values.
  • Sets are unordered collections of unique values.
  • Dictionaries are unordered collections of key-value associations.

So, You can not expect the same order, when you are iterating the values from Dictionary.

Reference to Collection Type

Subramanian P
  • 4,365
  • 2
  • 21
  • 25
0

Dictionary collection isn't ordered, that is it simply doesn't guarantee to be ordered. But Array is. Dictionary adds values in discrete orders whereas Array adds values in continuous order.

You simply can't have an Array like this:

["a", "b", ... , "d", ... , ... , "g"]    //Discrete index aren't allowed. You just can't skip any index in between.

Instead you have to have the above array like this:

["a", "b", "d", "g"] 

To be able to get rid of this behavior, Dictionary (where you don't have to maintain previous indexes to have values) was introduced. So you can insert values as you like. It won't bother you for maintaining any index.

nayem
  • 7,285
  • 1
  • 33
  • 51