Swift - Stored values order is completely changed in Dictionary

McDonal_11 picture McDonal_11 · Apr 13, 2015 · Viewed 23.9k times · Source

I tried to display datas which is in Dictionary format. Below, three attempts are there. First attempt, output order is completely changed. Second attempt, output order is same as input. But, in third attempt, I declared variable as NSDictionary. Exact output I received. Why this changes in Dictionary? Kindly guide me. I searched for Swift's Dictionary tag. But I couldn't found out.

//First Attempt
var dict : Dictionary = ["name1" : "Loy", "name2" : "Roy"]
        println(dict)

//output:
[name2: Roy, name1: Loy]

//Second Attempt
var dict : Dictionary = ["name2" : "Loy", "name1" : "Roy"]
        println(dict)

//output:
[name2: Loy, name1: Roy]
-----------------------------------------------------------

//Third Attempt With NSDictionary
var dict : NSDictionary = ["name1" : "Loy", "name2" : "Roy"]
            println(dict)

//output:
{
    name1 = Loy;
    name2 = Roy;
}

ANOTHER QUERY: I have used play ground to verify. My screen shot is below:

play_ground_screen_shot

Here, In NSDictionary, I gave name5 as first, but in right side name2 is displaying, then, in println, it is displaying in ascending order. Why this is happening??

play_ground_screen_shot_2

Here, In Dictionary, I gave name5 as first, but in right side name2 is displaying, then, in println, it is displaying, how it is taken on the Dictionary line. Why this is happening??

Answer

Schemetrical picture Schemetrical · Apr 13, 2015

This is because of the definition of Dictionaries:

Dictionary

A dictionary stores associations between keys of the same type and values of the same type in an collection with no defined ordering.

There is no order, they might come out differently than they were put in.
This is comparable to NSSet.


Edit:

NSDictionary

Dictionaries Collect Key-Value Pairs. Rather than simply maintaining an ordered or unordered collection of objects, an NSDictionary stores objects against given keys, which can then be used for retrieval.

There is also no order, however there is sorting on print for debugging purposes.