[英]Accessing a non raw type enumerations case values?
So I have an enumeration defined as the following:所以我有一个枚举定义如下:
enum CardPosition {
case top(CGFloat)
case middle(CGFloat)
case bottom(CGFloat)
}
I have a variable of type CardPosition that is defined as:我有一个 CardPosition 类型的变量,定义为:
@State private var position: CardPosition = CardPosition.bottom(UIScreen.main.bounds.height - 100)
How do I access the value of the CardPosition?如何访问 CardPosition 的值? In this case, I'm trying to access the UIScreen.main.bounds.height - 100 value from the enumeration.
在这种情况下,我试图从枚举中访问 UIScreen.main.bounds.height - 100 值。 I tried accessing it with
我尝试使用
self.position.rawValue
but unfortunately this doesn't work.但不幸的是,这不起作用。 Anyone know how I can access the CGFloat value of position?
任何人都知道如何访问 position 的 CGFloat 值?
You need to use a switch here:您需要在此处使用开关:
switch position {
case .top(let f):
// use f
case .middle(let f):
// use f
case .bottom(let f):
// use f
}
If you want it as an expression , you can do something like:如果你想要它作为一个表达式,你可以这样做:
// 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
}
}()
However, I think the best solution is to redesign your types.但是,我认为最好的解决方案是重新设计您的类型。 It seems like there will always be a
CGFloat
associated with every case of your enum.似乎总会有一个
CGFloat
与您的枚举的每个案例相关联。 Why not use a struct composing a simple enum and a 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)
}
}
Then you can easily access the number via position.offset
.然后您可以通过
position.offset
轻松访问该号码。
You can create a Computed Property position
inside the enum CardPosition
and return
the associated value with each case
, ie您可以在
enum CardPosition
内创建一个计算属性position
并return
每个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
}
}
}
To get the associated value for your .bottom
variable you use if let case
syntax要获取
.bottom
变量的关联值,请使用if let case
语法
var position: CardPosition = CardPosition.bottom(UIScreen.main.bounds.height - 100.0)
if case let CardPosition.bottom(positionValue) = position {
print(positionValue)
}
This will give you only a value for .bottom
and not for any of the other enum cases.这只会为您提供
.bottom
的值,而不是任何其他枚举案例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.