Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift Enums and Structs Enums and their Methods Initializer

Ross Freeman
Ross Freeman
5,522 Points

Is 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
Stone Preston
42,016 Points

the 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")
    println("Not a safe place for humans")
// prints "Mostly harmless
Ross Freeman
Ross Freeman
5,522 Points

Ok, that's what I was thinking. Thanks for the explanation!