Consider:
enum Line { case Horizontal(CGFloat) case Vertical(CGFloat) } let leftEdge = Line.Horizontal(0.0) let leftMaskRightEdge = Line.Horizontal(0.05)
How can I access, say, lefEdge
's associated value, directly, without using a switch statement?
let noIdeaHowTo = leftEdge.associatedValue + 0.5
This doesn't even compile!
I had a look at these SO questions but none of the answers seem to address this issue.
The noIdeaHowTo
non compiling line above should really be that one-liner, but because the associated value
can be any type, I fail to even see how user code could write even a "generic" get or associatedValue method in le enum itself.
I ended up with this, but it is gross, and needs me to revisit the code each time I add/modify a case ...
enum Line { case Horizontal(CGFloat) case Vertical(CGFloat) var associatedValue: CGFloat { get { switch self { case .Horizontal(let value): return value case .Vertical(let value): return value } } } }
Any pointer anyone?
In Swift enum, we learned how to define a data type that has a fixed set of related values. However, sometimes we may want to attach additional information to enum values. These additional information attached to enum values are called associated values.
In Swift language, we have Structs, Enum and Classes. Struct and Enum are passed by copy but Classes are passed by reference. Only Classes support inheritance, Enum and Struct don't.
You cannot make a function only available to one case of an enum. Any function in an enum is available to every case of the enum.
What is a Swift Enum? According to the Swift documentation enumeration is defined as “a common type for a group of related values and enables you to work with those values in a type-safe way within your code”. Think of it as a type of variable that is specifically used switch/conditionals.
As others have pointed out, this is now kind of possible in Swift 2:
import CoreGraphics enum Line { case Horizontal(CGFloat) case Vertical(CGFloat) } let min = Line.Horizontal(0.0) let mid = Line.Horizontal(0.5) let max = Line.Horizontal(1.0) func doToLine(line: Line) -> CGFloat? { if case .Horizontal(let value) = line { return value } return .None } doToLine(min) // prints 0 doToLine(mid) // prints 0.5 doToLine(max) // prints 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With