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

How would you make an enum return something dynamic?

In Amit's success/failure example, he mentions there could be multiple reasons for a failure. What if in one case, the reason for a failure is "Network connection unavailable" but in another case it's "Not enough memory" or even something else? Would you just create multiple constants (e.g. downloadStatusFailure1, downloadStatusFailure2) with different messages?

1 Answer

Felix Salazar
Felix Salazar
3,879 Points

No, the enum is only declaring all the possible status but not the messages, that's the String associated for. In fact, the message, as the exemple implies, is set at the moment you found what went wrong. Taking your supossition:

enum Status{
    case Succes, Failure(String)
}
/*InternetConnectionClass*/
if (!wifiConnection){
   // if the wifi is unavailable, you use the Status.Failure to alert the upper level class or something
   return Status.Failure("Network connection unavailable")
}
/*ImageRenderClass*/
if (!enoughMemory){
   // if not enough memory, you still use the same Status.Failure with another message
   return Status.Failure("Not enough memory")
}

Hope this helps!