Consider:
enum Line {
case Horizontal(CGFloat)
case Vertical(CGFloat)
}
let leftEdge = Line.Horizontal(0.0)
let leftMaskRightEdge
I think you may be trying to use enum
for something it was not intended for. The way to access the associated values is indeed through switch
as you've done, the idea being that the switch
always handles each possible member case of the enum
.
Different members of the enum
can have different associated values (e.g., you could have Diagonal(CGFloat, CGFloat)
and Text(String)
in your enum Line
), so you must always confirm which case you're dealing with before you can access the associated value. For instance, consider:
enum Line {
case Horizontal(CGFloat)
case Vertical(CGFloat)
case Diagonal(CGFloat, CGFloat)
case Text(String)
}
var myLine = someFunctionReturningEnumLine()
let value = myLine.associatedValue // <- type?
How could you presume to get the associated value from myLine
when you might be dealing with CGFloat
, String
, or two CGFloat
s? This is why you need the switch
to first discover which case
you have.
In your particular case it sounds like you might be better off with a class
or struct
for Line
, which might then store the CGFloat
and also have an enum
property for Vertical
and Horizontal
. Or you could model Vertical
and Horizontal
as separate classes, with Line
being a protocol (for example).