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!

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

Max Howarth
Max Howarth
2,605 Points

What is the advantage of using an enum over a class in this example?

I'm wondering what the advantage to using an enum over a class in this example is. I can sense that there is some kind of advantage, but I'm having trouble wrapping my head around it.

If I were to use the following code, I would be able to have a class called RGBColour that I could call to assign an instance of UIColour to a variable or constant.

class RGBColour {

    var red: CGFloat
    var blue: CGFloat
    var green: CGFloat
    var alpha: CGFloat

    init(red: CGFloat, blue: CGFloat, green: CGFloat, alpha: CGFloat){
        self.red = red
        self.blue = blue
        self.green = green
        self.alpha = alpha
    }

    func color() -> UIColor {

        return UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: alpha)
    }
}

let someColor = RGBColour(red: 100, blue: 19, green: 20, alpha: 1)
someColor.color()

I could create another such class for HSB.

The advantages I see for an enum here are:

  1. You can combine both RGB and HSB colour definitions into 1 object. (This would probably have more value in another circumstance?)

  2. You can call the enum without assigning it to a variable. But I don't understand where this would be useful?

Can you please elaborate a bit on how an enum is more helpful for us in this example?

Thanks!