繁体   English   中英

访问非原始类型枚举案例值?

[英]Accessing a non raw type enumerations case values?

所以我有一个枚举定义如下:

enum CardPosition {
    case top(CGFloat) 
    case middle(CGFloat)
    case bottom(CGFloat) 
}

我有一个 CardPosition 类型的变量,定义为:

@State private var position: CardPosition = CardPosition.bottom(UIScreen.main.bounds.height - 100)

如何访问 CardPosition 的值? 在这种情况下,我试图从枚举中访问 UIScreen.main.bounds.height - 100 值。 我尝试使用

self.position.rawValue 

但不幸的是,这不起作用。 任何人都知道如何访问 position 的 CGFloat 值?

您需要在此处使用开关:

switch position {
case .top(let f):
    // use f
case .middle(let f):
    // use f
case .bottom(let f):
    // use f
}

如果你想要它作为一个表达式,你可以这样做:

// you can assign the below to a variable or whatever
// let value =
{ () -> CGFloat in
    switch position {
    case .top(let f):
        return f
    case .middle(let f):
        return f
    case .bottom(let f):
        return f
    }
}()

但是,我认为最好的解决方案是重新设计您的类型。 似乎总会有一个CGFloat与您的枚举的每个案例相关联。 为什么不使用由简单枚举和CGFloat组成的结构?

enum RelativeCardPosition {
    case top
    case middle
    case bottom
}

struct CardPosition {
    let relativeCardPosition: RelativeCardPosition
    let offset: CGFloat
    
    static func top(_ offset: CGFloat) -> CardPosition {
        CardPosition(relativeCardPosition: .top, offset: offset)
    }
    
    static func middle(_ offset: CGFloat) -> CardPosition {
        CardPosition(relativeCardPosition: .middle, offset: offset)
    }
    
    static func bottom(_ offset: CGFloat) -> CardPosition {
        CardPosition(relativeCardPosition: .bottom, offset: offset)
    }
}

然后您可以通过position.offset轻松访问该号码。

您可以在enum CardPosition内创建一个计算属性positionreturn每个case的关联值,即

enum CardPosition {
    case top(CGFloat)
    case middle(CGFloat)
    case bottom(CGFloat)
    
    var position: CGFloat {
        switch self {
        case .top(let pos), .middle(let pos), .bottom(let pos):
            return pos
        }
    }
}

要获取.bottom变量的关联值,请使用if let case语法

var position: CardPosition = CardPosition.bottom(UIScreen.main.bounds.height - 100.0)

if case let CardPosition.bottom(positionValue) = position {
    print(positionValue)
}

这只会为您提供.bottom的值,而不是任何其他枚举案例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM