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 trial

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.