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?

Code for extra credit challenge

What's the written code for this challenge?

Create an array of 10 songs where each song is a dictionary. The dictionary contains the following keys: title, artist and album.

2 Answers

Hi there,

A dictionary is created like:

let exampleDict = ["title": "Yellow", "artist": "Coldplay", "album": "Parachutes"]

That can be accessed by the key/value pair - they have no order. exampleDict["title"] would be "Yellow", for example.

You need an array of these. Arrays are defined inside square brackets and separated by commas. They are ordered and accessed by square bracket notation. let anArray = ["a", "b", "c"] means that anArray[1] is "b". You can place your 10 dictioaries between square brackets and separate them with commas to acheive your result. Something like:

let songArray = [
    ["title": "Yellow", "artist": "Coldplay", "album": "Parachutes"],
    ["title": "Belong", "artist": "REM", "album": "Out of Time"],
    ["title": "Run", "artist": "Snow Patrol", "album": "Final Straw"]
]

You can access this by combining the two methods above - songArray[0]["title"] gives you "Yellow". To get the result "Out of Time", you could use songArray[1]["album"] - (I did check!!). You define the position in the array first with square brackets and a number (zero-based), that produces the entire dictionary as a result, so you can then use the key, in this case "album" to drive down to the result.

Apologies, I got bored after three dictionaries - I'm sure you can figure out the rest! :-)

Hope that helps, else just shout if you need more.

Steve.

Thank you Steve. This made it crystal! :)

No problem - glad to help! :-)