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

A Question regarding the contents in the switch function

let downloadStatus = Status.Failure("Network connection unavailable")

switch downloadStatus {
case .Success(let success):
    println(success)
case .Failure(let failure):
    println(failure)

Why is there a need for the case . Success? The constant let downloadStatus = Status.Failure(String) is always a failure. I understand that switch has to be exhausted, but shouldn't it be a case default instead of .Success?

Thanks,

1 Answer

Brenden Konnagan
Brenden Konnagan
16,858 Points

Hello Duc,

Really it would come down to at least two items:

  • API Design
  • Code Style | Readability

API Design

While at this time there may be no use for the "Success" call, perhaps there could be more functionality built in at a later date.

Code Style | Readability

This is a big one. While "Default:" will function fine it would not lead to very readable code as "Default:" does not necessarily convey to any reader when that could be called.

You are correct that a switch statement needs to be exhaustive. It is generally bad form to rely on "Default:" cases since a switch statement in itself is explicit.

Granted there are times where all cases are unknown or not able to be inferred and thus "Default:" is a great fit. Otherwise it is always best to account for all the cases explicitly.