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 trialDaan van Klinken
1,744 PointsWhy doesn't this Switch statement use a *default* case?
The Switch statement in the example only uses two cases. Doesn't it always need a default case? So in this example it would be case .Failure: and default: ...
Example from the video:
enum Status {
case Success(String)
case Failure(String)
}
let downloadStatus = Status.Failure("Network connection unavailable")
switch downloadStatus {
case .Success(let success):
println(success)
case .Failure(let failure):
println(failure)
}
1 Answer
J.D. Sandifer
18,813 PointsThis is a great question!
Every switch statement does indeed need to be exhaustive - that is, it must have a case for every possible value. Sometimes, this in ensured by having a default
case to catch any unexpected values. However, for this enum where all possible values are defined in the code, it's easy to know that we're catching every possible value in the switch statement.
Daan van Klinken
1,744 PointsDaan van Klinken
1,744 PointsUpdate. found the answer:
https://teamtreehouse.com/forum/is-a-default-case-necessary-in-a-method
If the Switch statement covers all the items already, you don't need to specify a default, if you leave some enum items unspecified, you need to add a default.