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

Ryan Anderson
Ryan Anderson
2,920 Points

What am I supposed to do with this var?

So I've written this if let statement that checks if there's a Movie called Spectre, that there's a cast list, and then assigns leadActor to the first thing in the array.

Thing is, I've assigned the var within the if let, so it's temporary. I've tried making the if let part of the var, but that didn't work.

Any suggestions?

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 let movie = movieDictionary["Spectre"], let castList = movie["cast"] {
    var leadActor = castList[0]
}

2 Answers

It looks really good and it seems you understand the optional unwrapping part. The only thing you have missed is that you are defining a new var leadActor inside the if let block scope. You should just access the current leadActor. You need to leave the var off inside your block.

if let movie = movieDictionary["Spectre"], let castList = movie["cast"] {
    leadActor = castList[0] // this will assign the result to the leadActor already declared
}
Ryan Anderson
Ryan Anderson
2,920 Points

Okay - that makes sense... what I ended up doing was this:

var leadActor: String {
    if let movie = movieDictionary["Spectre"], let castList = movie["cast"] {
        let actor = castList[0]
        return actor
    }
    return "There isn't a lead actor."
}

It passed, but I can see how clunky it is now.

You can do it that way if you have all that info at the time you are declaring your leadActor variable. You may want to think about what you would do if you later wanted to go into the movieDictionary and return a different leadActor somewhere else in your code. Good luck and keep learning!