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
Roger Panella
5,968 PointsQuestion about code challenge: Array[0] isn't optional?
I was able to write code that passed the code challenge, but looking at Xcode errors I saw as I was doing it brought up a question. This is my passing code:
let movieDictionary = ["Spectre":
["cast":
["Daniel Craig", "Christoph Waltz", "Léa Seydoux", "Ralph Fiennes", "Monica Bellucci", "Naomie Harris"]
]
]
var leadActor = ""
if let movieTitle = movieDictionary["Spectre"],
let movieCast = movieTitle["cast"] {
leadActor = movieCast[0]
print(leadActor)
}
However, if I try to make "leadActor = movieCast[0]" a part of the "if let", I get the error: "Initializer for conditional binding must have Optional type, not 'String'" To fix it, I moved the first curly bracket in the if/let to be after the "let movieCast" line, removed "let" from the next line.
My question is: Isn't is possible that movieCast[0] would be nil? And, if I looked for the array value [0] of an empty array, wouldn't that cause a crash/error?
1 Answer
Steven Deutsch
21,046 PointsHey Roger Panella,
Great question. When you subscript an array the value returned is not an optional. This differs from dictionaries. Whenever you look up a value in a dictionary using a key, the value is always returned as an optional. To further answer your question, yes, anytime you subscript an array with an index that is out of range - you will get a run time error and your program will crash.
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"] {
leadActor = cast[0]
}
Good Luck!
Roger Panella
5,968 PointsRoger Panella
5,968 PointsI'm not sure why this isn't connected to the video I asked the question on. I was on the questions section for that video, then clicked "Ask", so this probably doesn't make sense out of context.
I'm referring to the code challenge after the Optional Binding video in "Swift 2.0 Enumerations and Optionals"