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

Martel Storm
Martel Storm
4,157 Points

Nil Values in Optionals. Stuck Code Challenge.

What am I missing here?

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

var leadActor: String = ""

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

1 Answer

andren
andren
28,558 Points

The problem comes from the fact that you use the name leadActor for your unwrapping. By doing that you create a new array variable named leadActor within the scope of that if code block, that while named the same does not actually equal the leadActor variable outside the if block.

If you choose a different name like this:

if var actors = movieDictionary["Spectre"], let person = actors["cast"] {
  leadActor = person[0]
}

Then your code will work fine.