Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,352 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 )