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 Associated Values

Why 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)
}

Update. 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.

1 Answer

J.D. Sandifer
J.D. Sandifer
18,813 Points

This 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.