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 trialRoss Freeman
5,522 PointsIs a default case necessary in a method?
So I decided to complete the dayString() method by adding in all of the possible case statements. I noticed that Xcode doesn't throw an error after creating cases for all 7 days even though there is no default. Since it looks like Xcode can detect if every case of an enum is considered in a method, is there any reason to include a default case anyway?
1 Answer
Stone Preston
42,016 Pointsthe Swift eBook states:
a switch statement must be exhaustive when considering an enumerationβs members
since you provided a case for every member, that switch is exhaustive since every possible enumeration case is present. there does not need to be a default because all the values are covered.
However, had you not provided a case for every member and left a few out, you would need to provide a default case in order to be exhaustive
When it is not appropriate to provide a case for every enumeration member, you can provide a default case to cover any members that are not addressed explicitly
the example from the eBook below only provides one case and then a default value for the rest. this switch is exhaustive since .Earth is covered in the case, and everything else is covered by the default
let somePlanet = Planet.Earth
switch somePlanet {
case .Earth:
println("Mostly harmless")
default:
println("Not a safe place for humans")
}
// prints "Mostly harmless
Ross Freeman
5,522 PointsRoss Freeman
5,522 PointsOk, that's what I was thinking. Thanks for the explanation!