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?

I am having a trouble with understanding Extra Credit task in Functions with Dictionary

HI,

The task goes:

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 have so much trouble with tuples. I need help.

4 Answers

First of all, you should think of songDictionary as a parameter, as they are called in Swift. It's the input that you use to get the output.

As for the type, just be happy there's a shorthand. The regular notation involves angle brackets, and can get fairly complicated in certain circumstances.

Here's the code snippet I tried to show you last time:

func getSongInfo(songDictionary: [String: String]) -> (title: String, artist: String, album: String) {
    // You can figure out what goes on in here.
}

The parameter (insideTheParentheses) is the dictionary. The return value, after the ->, is the tuple.

Okay, this is a function that will extract the three values in a given dictionary, and they want it in a named tuple. What this means is along with specifying the return type for each value (String for each), they want a name that references each value within the tuple. This allows you to later extract a value from that tuple with a recognizable name, rather than just an index.

'''swift func getSongInfo(songDictionary: [String: String]) -> (title: String, artist: String, album: String) { // You can figure out what goes on in here. } '''

After the function declaration, you could save the return value to a variable, then access, for example, the title value like this: songTuple.title PS - have you tried saving each value in the dictionary to a variable before returning the tuple? It makes your code a lot more readable.

Yes I did.

This syntax is new to me: (songDictionary: [String: String])

songDictionary is my variable or better to say named tuple, but why do I have to put type in brackets. Is this only dictionary thing when passing an arguments or...?

I think I get the concept, though I still must memorize the syntax. Thanks for all the help. I think I better understand return values also, I thought that only one word can be after return arrow.