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

I need help on extra credit

Extra Credit:

Im pretty stumped on this extra credit: Write a function that accepts a Dictionary as parameter and returns a named tuple. The dictionary should contain the following keys: title, artist and album.

I am kind of confused on what its asking me to do exactly and I also have no idea where to start.

Traci McGrew
Traci McGrew
2,559 Points

I'll help you break it down:

Create dictionary to hold the song info (you did this before if you're working your way through the Swift courses for an early exercise.) If you're still stuck go back and look at how to make a dictionary. In this case you need a dictionary to hold info for one song with the keys being title, artist, and album.

Next write a function that as a parameter gets this dictionary passed into it as a parameter. This was shown also in previous videos in this track. Review them if you need help. The function will also return title, artist, and album as Strings. Inside the function declare variables to hold what was passed in and assign them appropriately. Next declare tuple put those into it and then return the tuple.

Now test what you did is working:

Call the function and store the returned result in a tuple. Print it to the console. Declare another dictionary, call function again, print it again if everything is working then great!

Hope this helps. Please try the exercise. If you get stuck and can't find your error, post your code and me or someone else can help point you in the right direction.

1 Answer

William Ye
William Ye
3,188 Points

Hi this is the code I got for the extra credit activity to work. What I didn't understand however was the need to put the ! after my constants. That was the only way I got it to work.

import UIKit

let song = [
    "title": "King Kunta",
    "artist": "Kendrick Lamar",
    "album": "To Pimp a Butterfly"
]


func findSongInfo (song: Dictionary <String, String>) -> (title: String, artist: String, song: String) {

    let songTitle: String = song["title"]!
    let songArtist: String = song["artist"]!
    let songAlbum: String = song ["album"]!

    var songInfo = (songTitle, songArtist, songAlbum)
    return songInfo
}

findSongInfo(song).title

You had to add the ! at the end of your constants to unwrap the element in the dictionary from an Optional.