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!

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 Enumerations and Optionals in Swift Introduction to Optionals Nil Values in Collections

Joel Crouse
Joel Crouse
4,727 Points

Need help: Enums and Optionals in Swift code challenge

I'm kinda new to Swift so I'm probably making a really obvious mistake somewhere but I'm stuck and need help passing this code challenge. Thanks in advance!

let movieDictionary = ["Spectre": ["cast": ["Daniel Craig", "Christoph Waltz", "LÊa Seydoux", "Ralph Fiennes", "Monica Bellucci", "Naomie Harris"]]]

var leadActor: String = ""

// Enter code below
if let movie = movieDictionary["Spectre"], let cast = movie["cast"], let leadActor = cast[0] {


1 Answer

Heidi Puk Hermann
Heidi Puk Hermann
33,366 Points

Hi ,

you need to access each array/dictionary at a time, starting from the outside and going in. (Really hope this will make sense :) )

Imagine that you are building an app where people can store all their clothes. Each person has their own row, which contains a number of dictionaries - one for each type of clothes. The types of clothes are sorted by colour (just to have the same type of structure as you have...).

var clothesDictionary = [
   "person1": ["shirts": ["blue", "black"], "pants": ["black", "white"]], 
   "person2": ["shirts": ["pink", "red"], "pants": ["cowboy", "black"]]

/* Access the colour of the second pair of pants for person2... 
    - Since I don't know if I have a person2, I have to check if he exists first.
    - Then check if he has any pants, and then I can get out the colors.*/

if let person = clothesDictionary["person2"], let pants = person["pants"] {
   var secondPantsColor: String = pants[1]

Hope that it can help you :)

(Disclaimer: It is a copy of my exact same answer to a similar question yesterday :), If it does not make sense to you, just let me know, then I can elaborate in relation to the actual code-challenge \H )