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 trialJoe Scotto
8,282 PointsWhy 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
14,575 PointsHello:
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