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 Basics (retired) Collections What is a Dictionary?

When do you use Dictionaries vs using an array?

Can someone provide examples of when to use dictionary vs using an array? Amit mentioned using array for a todo list since it is ordered. So is the rule basically, if the items need to be in order, you always use an array? Or are there exceptions?

1 Answer

Nathan F.
Nathan F.
30,773 Points

That's a good general rule of thumb. A dictionary is basically, well... a dictionary--items are associated by key-value pairs and could be returned in any order. That is, accessing the first item in a dictionary might not be what you expect it to be.

Dictionaries are best used in cases where you look up one value to find another (or multiple values) associated with it. Some good examples are given in the Swift course, such as having a dictionary listing country codes with their associated country. Ex:

let countryCodes = ["US": "United States", 
                                  "KR": "South Korea", 
                                  "GB": "Great Britain", 
                                  "IN": "India"]

You might use the "US" country code in one part of your application, but need the full country name elsewhere in the app. You can use the dictionary to look up one value or the other and return the other part of the pair.

Got it. Thanks Nathan Fulkerson .

Nathan F.
Nathan F.
30,773 Points

Glad I could help, Jay.