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?

How would you go about solving the extra credit question? Q: Create an array of 10 songs where each song is a dictionary


3 Answers

I can think of two simple ways to do it:

var songs = [
    ["title": "title1", "artist": "artist1", "album": "album1"],
    ["title": "title2", "artist": "artist2", "album": "album2"],
    ["title": "title3", "artist": "artist3", "album": "album3"],
    // 4, 5, 6,... 10, etc.
var songs:[Dictionary<String, String>] = []

for i in (1...10) {
    songs.append(["title": "title\(i)", "artist": "artist\(i)", "album": "album\(i)"])

Rock solid. Thanks for your help brochacho.

@krilnon, for the first one, I would I call out just the 1st "artist"?

I think is might be useful for you

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

import UIKit

//Dictionary 1 var songsDic = [ "title": "Song Title 1", "artist": "Artist Name 1", "album": "Album Name 1"]

//Dictionary 2 var songsDic2 = [ "title": "Song Title 2", "artist": "Artist Name 2", "album": "Album Name 2"]

//Dictionary 3 var songsDic3 = [ "title": "Song Title 3", "artist": "Artist Name 3", "album": "Album Name 3"]

//Aray of three songs where each song is a dictionary var songs = [ songsDic, songsDic2, songsDic3]

Lauren Hibbs
Lauren Hibbs
1,872 Points

This is what I did for my extra credit. I didn't really want to do ten songs though. The first four variables are my dictionary items, with title, artist and album defined. The fifth variable is my array which contains variables which each represent a dictionary.

import UIKit

var noSunlight = ["Title":"No Sunlight" ,"Artist":"DCFC","Album":"Narrow Stairs"]

var longDivision = ["Title":"Long Division" ,"Artist":"DCFC","Album":"Narrow Stairs"]

var blackSun = ["Title":"Black Sun" ,"Artist":"DCFC","Album":"Kintsugi"]

var nugget = ["Title":"Nugget" ,"Artist":"Cake","Album":"Fashion Nugget"]

var songs = [noSunlight,longDivision,blackSun,nugget]

// just to test out that my array works...

blackSun["Title"] // "Black Sun"

songs[0]["Album"] // "Narrow Stairs"

songs[3]["Artist"] // "Cake"