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

Josh Schlabach
Josh Schlabach
1,771 Points

Why isn't this correct?

So after watching the enum videos, I've been wondering... What would we use associated values for? Can someone give me a real life example?

Thanks!

enum.swift
enum BookType {
case Pdf(String)
case Epub(String)

var book = BookType.Pdf: ("Game of Thrones")

1 Answer

Jason Safdie
Jason Safdie
3,461 Points

Check out my code. You were close, but your syntax was a little off. As for real life examples, the ability to assign associated values to a member value within an Enum gives you the ability to specify a different data type. So, within a menu on an app, you could have a small number of choices for the user to select that represent different data types (e.g. String, Int, etc.). I'm pretty sure that's the use case, but I could be wrong.

enum BookType {
    // Write your members with associated values here
  case Pdf (String)
  case Epub (String)

}

var book = BookType.Pdf("Game of Thrones")