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

后端 未结 5 1664
我寻月下人不归
我寻月下人不归 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:49

    Why this is not possible is already answered, so this is only an advice. Why don't you implement it like this. I mean enums and structs are both value types.

    enum Orientation {
        case Horizontal
        case Vertical
    }
    
    struct Line {
    
        let orientation : Orientation
        let value : CGFloat
    
        init(_ orientation: Orientation, _ value: CGFloat) {
    
            self.orientation = orientation
            self.value = value
        }
    } 
    
    let x = Line(.Horizontal, 20.0)
    
    // if you want that syntax 'Line.Horizontal(0.0)' you could fake it like this
    
    struct Line {
    
        let orientation : Orientation
        let value : CGFloat
    
        private init(_ orientation: Orientation, _ value: CGFloat) {
    
            self.orientation = orientation
            self.value = value
        }
    
        static func Horizontal(value: CGFloat) -> Line { return Line(.Horizontal, value) }
        static func Vertical(value: CGFloat) -> Line { return Line(.Vertical, value) }
    }
    
    let y = Line.Horizontal(20.0)
    

提交回复
热议问题