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

Further Explanation of Associated Values of Enum

While enums and raw values are ok, I'm having a hard time wrapping my head around associated values. Is the associated value like a property of the member? Is the associated value separate or linked to the member? Why use associated values?

Any help or examples would be appreciated.

1 Answer

The Apple docs describe associated values very well. I would suggest reading their explanation to get the full understanding (when in doubt, always check the Apple docs). https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Enumerations.html

Basically, the associated value specifies what the value type of the member should be. In their example, they have...

enum Barcode {
    case UPCA(Int, Int, Int, Int)
    case QRCode(String)
}

...the associated value of UPCA should be 4 Int values, while QRCode is just a single string, but they're both still barcodes and new barcodes added can be added as either type, provided their input matches the associated value format.