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
Edwin Escobar
4,594 PointsWhy isn't it possible to 'switch nil' on Swift?
Why is this posible with if but it isn't with switch?
func addChoice (title: String, page: Page) -> Page {
if firstChoice == nil {
firstChoice = (title, page)
} else if secondChoice == nil {
secondChoice = (title, page)
}
return page
}
func addChoice2 (title: String, page: Page) -> Page {
switch nil {
case firstChoice: firstChoice = (title, page)
case secondChoice: secondChoice = (title, page)
default: break
}
return page
}
2 Answers
Kieran Black
9,139 PointsHi Edwin,
nil is a value (well an absence of a value, in the way that black is the absence of colour but classed as a colour), there is no point switching on a value as it will always be the same, it's not variable.
Your switch should be on a variable and the nil should be within a case.
There isn't enough code in your specific case to be able to provide an example on it, for example what is Page and how are ** firstChoice** and ** secondChoice** provided to the function.
Hope that helps.
KB
Edwin Escobar
4,594 PointsThanks. Well, switch can work with static values as it is written on the documentation, so I don't think thats the problem.
firstChoice and secondChoice are optionals, so they can be nil and it works with the if statement, then I don't see why switch is incapable of taking nil.