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

Gavin Hobbs
Gavin Hobbs
5,205 Points

Explain Enums in a Relatable Way

Hi all!

I am learning iOS development and I can't quite understand enums and how they work. I've tried plowing ahead thinking eventually it will click, but that hasn't happened yet. I'm hoping someone can explain enums in a way you can easily understand it. For reference, I really like pictures such as the one in the JavaScript course of a race track in which Dave McFarland was explaining loops.

Thanks a million!

  • Gavin

1 Answer

Ignazio Calo
PLUS
Ignazio Calo
Courses Plus Student 1,819 Points

Enun is a type of variable, like Int or bool.

Each type of variable can contains only specific values. For example an Int can contains only numbers, a boolean can contain only true or false. But what about if you need a variable that can contain only your custom list of values? For example you need a variable to store the grade at your school, that's is only "a", "b", "c", "d", "e", "f" ? of course you can use an int variable for this, or even a string, but wouldn't be more explicit if your variable could only have those values? yes, it would :) and in facts is possible

enum Grade {
    case a
    case b
    case c
    case d
    case e
    case f
}

var enumFinalGrade: Grade = Grade.a //<- this is awesome
var stringFinalGrade: String = "a" // <- this is error prone
var stringFinalGrade = "foobar" // <- this is valid for the compiler, but doesn't make any sense

In swift enums are more complicated then this, because you can have associated values with each value, but go step by step. Grasp the basic enum idea, then move to the more advanced usages.

Gavin Hobbs
Gavin Hobbs
5,205 Points

Thanks Ignazio Calo ! Super helpful and very insightful!