Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a Swift enum associated value outside of a switch statement

Tags:

enums

swift

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?

like image 929
verec Avatar asked Jul 11 '15 16:07

verec


People also ask

What is associated value in enum Swift?

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.

Can enum inherit Swift?

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.

Can a Swift enum have functions?

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.

How does enum work in Swift?

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.


1 Answers

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 
like image 170
verec Avatar answered Oct 11 '22 22:10

verec