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 Collections Extra credit?

I'm trying to do the extra credit with the song titles and names, I like the way it's done in this example....

var songs: [Dictionary<String, String>] = [
    [
        "title": "Back in Black",
        "artist": "Metallica",
        "album": "Neverland"
    ],
    [
        "title": "Back in Red",
        "artist": "Metallica",
        "album": "Neverland"
    ]
    // ...
]

However, the [Dictionary<String, String>] is throwing me off. I read it wasn't necessary so how would it look minus that line?

1 Answer

You could do without that in one of 2 ways. You could:

  • Format it differently, like this:
//Declaring it as [[String : String]] is exactly the same as declaring it as [Dictionary<String, String>], but with fewer characters
var songs: [[String : String]] = [
    [
        "title": "Back in Black",
        "artist": "Metallica",
        "album": "Neverland"
    ],
    [
        "title": "Back in Red",
        "artist": "Metallica",
        "album": "Neverland"
    ]
    // ...
]
  • Delete the explicit declaration altogether and let the compiler infer the type, like this:
//In this, you don't even tell the compiler what type songs is, but it can guess it itself
var songs = [
    [
        "title": "Back in Black",
        "artist": "Metallica",
        "album": "Neverland"
    ],
    [
        "title": "Back in Red",
        "artist": "Metallica",
        "album": "Neverland"
    ]
    // ...
]

I was looking for the method that let the compiler infer the type. Just for future reference how would you call each arrary to display the title,artist and album?

If you wanted to get the title of the first Dictionary in the Array, you would use this line, for example:

//The first set of square brackets (with the Int) specifies what Dictionary in the Array you want
                  |   //The second set of square brackets (with the String) specifies what index of the Dictionary you want
                  |     |
let black = songs[0]["title"]

The above would cause the constant black to be equal to the String "Back in Black"