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

Edward Palmer
Edward Palmer
3,313 Points

I'm struggling with an extra credit challenge on the swift track, could anyone help?

I can't work out how to build dictionaries into a function. Any examples / pointers would be appreciated. Here's the question:

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.

1 Answer

Hi Edward,

I'm not an expert but here's a little bit of code I just lashed together that will hopefully give you some pointers?

let dict:[String: String] = ["title" : "a song", "artist" : "a singer", "album" : "an album"]

func takesADictionary (dict:Dictionary<String, String>) -> (tuple1: String, tuple2: String) {
    let tuple1 = dict["artist"]
    let tuple2 = dict["album"]
    return (tuple1: tuple1!, tuple2: tuple2!)

}

takesADictionary(dict)

Have fun!!

Steve.

Hi Steve,

Can you please explain what the '!' does:

return (tuple1: tuple1!, tuple2: tuple2!)

Hi Ingvi,

I'm not the best to try and explain that, unfortunately. I don't fully understand it myself, fully!

However, I'll give it a go!

Swift is keen on use of 'Optionals'. This enables a variable to contain a data type or a nil. One use of this is to buld a fail-safe when accessing data objects like dictionaries or JSON streams. Since the attempt to access the dictionary may fail, assigning the attempt into an optional covers this scenario. When 'unwrapping' the optional, code will cover the eventuality that the variable may contain nil rather than the value or data type you were expecting. This prevents your code throwing an unexpected exception, allowing the code to manage the failed data assignment gracefully, rather than grinding to an unceremonious halt.

The 'bang' character is used to unwrap the optional, I think, revealing the value stored behind the scenes.

I'd strongly recommend ignoring the above and taking Amit's Swift course as he does a far better job of making sense!

Steve.