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

后端 未结 5 1672
我寻月下人不归
我寻月下人不归 2021-01-31 07:08

Consider:

enum Line {
    case    Horizontal(CGFloat)
    case    Vertical(CGFloat)
}

let leftEdge             =  Line.Horizontal(0.0)
let leftMaskRightEdge             


        
5条回答
  •  悲哀的现实
    2021-01-31 07:46

    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 CGFloats? 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).

提交回复
热议问题