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 2.0 Enumerations and Optionals Introduction to Enumerations Associated Enums

Why to add a string associated Value to the next exercise?

In the next exercise we defined an enum called MobilePhone, which has 4 cases. To each one we add an associated String value.

enum MobilePhone { case iPhone(String) case Android(String) case Blackberry(String) case Windows(String) }

Then we assign an enum to a constant named iPhone.

let iPhone = MobilePhone.iPhone("6S"). Why would we let the user write the string "6S". Should not we add it as a case in the enum? Were not we avoiding writing strings in the code?

Paul Brazell
Paul Brazell
14,371 Points

This is just an example of associated values in Swift Enumerations. The associated value could be of any data type, even another enum. A practical use case would be if you were adding string text from a text field as an associated value to an enum.

2 Answers

Paul Brazell
Paul Brazell
14,371 Points

This is just an example of associated values in Swift Enumerations. The associated value could be of any data type, even another enum. A practical use case would be if you were adding string text from a text field as an associated value to an enum.

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

Paul gave a good answer in the comments under the question. I'm just posting this so the question will show as "answered." To save you from scrolling, here's what Paul wrote:

This is just an example of associated values in Swift Enumerations. The associated value could be of any data type, even another enum. A practical use case would be if you were adding string text from a text field as an associated value to an enum.