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

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)
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")
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!