Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift 2.0 Collections and Control Flow Dictionaries Introduction to Dictionaries

Danny White
Danny White
7,107 Points

How does Swift decide the order of the dictionary?

Pasan mentions that a dictionary does not follow a strict order like an array. How is the output (on the right hand side) deduced? Why is HKG first, and then followed by LGA?

3 Answers

Steven Deutsch
Steven Deutsch
21,046 Points

Hey Danny White,

There is no order. Dictionaries in Swift are an unordered collection type. The order in which the values will be returned cannot be determined. If you need an ordered collection of values, I recommend using an array.

If you need to iterate over a dictionary in some specific order, you can use the sort() method on its keys or values property to iterate conditionally.

Hope this helps. Good Luck!

Alexander Smith
Alexander Smith
10,476 Points

Dictionaries use keys just like an array uses index values. If you want a value in an array, you select the corresponding index value which are ordered. In a dictionary u simply select the key to get its value. If you had an array of 100 items and say u wanted to select a value in the middle of that array you would have to count up to that point in order to select the proper index position. In a dictionary, use the value's key. To answer your question, you can put HKG last and LGA first or whatever in between. You still select its value using a key. The order is irrelevant

Jeff Neubauer
Jeff Neubauer
2,111 Points

I have the same question: How is the order in the output for a dictionary determined? I know there are ways to get around it, however I am just curious about the logic behind the order. Why can the order not be determined? Is it just that we don't know the method it uses? But someone does know that method. Or is it that no one knows how the order is created?