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
Julien Schmitt
2,334 PointsConditional binding error?
Hi guys,
I'm working on optionals and I'm encountering the following error: " Initializer for conditional binding must have Optional Type, not "String".
let mobilePhone = ["Apple": ["iPhone": ["6", "6S", "6S+"]]]
if let smartphone = mobilePhone["Apple"],
let phoneBrand = smartphone["iPhone"],
let phoneModel = phoneBrand[0] {
print(phoneModel)
}
Would be great if someone could help on this one.
Cheers !
3 Answers
Michael Hulet
47,913 PointsWhen you get a value from an array, the resulting value is not an Optional, as it is when getting a value from a dictionary. In other words, you can't get values from an array in an if let statement, unless the value inside the array is an optional. That being the case, the 3rd assignment in your optional assignment chain can't be there, and you have to move it into the if block itself, like this:
if let smartphone = mobilePhone["Apple"], let phoneBrand = smartphone["iPhone"]{
print(phoneBrand[0]) //phoneBrand[0] is equivalent to phoneModel from your example
}
Julien Schmitt
2,334 PointsHi Michael,
Thanks for the answer.
However what I don't understand here is that I copied the exercice we got and just replaced the values with my own ones just to test.
Here was the exercice:
let movieDictionary = ["Spectre": ["cast": ["Daniel Craig", "Christoph Waltz", "Léa Seydoux", "Ralph Fiennes", "Monica Bellucci", "Naomie Harris"]]]
var leadActor: String = ""
if let movie = movieDictionary["Spectre"],
let cast = movie["cast"] {
leadActor = cast[0]
print(leadActor)
}
Why is it working with the example above? Is it because it's a dictionary? If so, I don't see the differences between the constant movieDictionary and the constant mobilePhone.
Thanks,
Julien
Michael Hulet
47,913 PointsIt's working there because leadActor is defined outside of the if let chain. You just can't put the declaration of leadActor inside that list of if let declarations, because it is not an Optional
Julien Schmitt
2,334 PointsI see.
Thanks for the explanations !