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

Joe Scotto
Joe Scotto
8,282 Points

Why can I not assign "cast" to a variable before using it in the if let?

I have solved the challenge but am curious as to why one version works, and the other does not.

Working code

if let movie = movieDictionary["Spectre"],
   let cast = movie["cast"] {
     leadActor = cast[0]
}

error: initializer for conditional binding must have Optional type, not 'String'

if let movie = movieDictionary["Spectre"],
    let cast = movie["cast"],
    let lead = cast[0] {
      leadActor = lead
}

1 Answer

Jhoan Arango
Jhoan Arango
14,350 Points

Hello:

As the error message suggest, it tells you that it "must" be an optional type, and not a "String". At some point in your chain, it stops being an optional, because you already unwrapped it. Therefore it stops the "unwrapping" process.

if let movie = movieDictionary["Spectre"],
    let cast = movie["cast"],
    let lead = cast[0] { // This returns a String, which is the value you were looking for, and it should be outside the chain.
    leadActor = lead
}

I hope this helps you.

Good luck