Swift 具有原始值的枚举
为什么我不能用这样的原始值定义枚举Swift 具有原始值的枚举,swift,rawrepresentable,Swift,Rawrepresentable,为什么我不能用这样的原始值定义枚举 enum Edges : (Double, Double) { case TopLeft = (0.0, 0.0) case TopRight = (1.0, 0.0) case BottomLeft = (0.0, 1.0) case BottomRight = (1.0, 1.0) } : 原始值可以是字符串、字符或任何整数或浮点数类型 但有一种替代方案适合您: enum Edges { case TopLeft
enum Edges : (Double, Double) {
case TopLeft = (0.0, 0.0)
case TopRight = (1.0, 0.0)
case BottomLeft = (0.0, 1.0)
case BottomRight = (1.0, 1.0)
}
:
原始值可以是字符串、字符或任何整数或浮点数类型
但有一种替代方案适合您:
enum Edges {
case TopLeft
case TopRight
case BottomLeft
case BottomRight
func getTuple() -> (Double, Double) {
switch self {
case .TopLeft:
return (0.0, 0.0)
case .TopRight:
return (1.0, 0.0)
case .BottomLeft:
return (0.0, 1.0)
case .BottomRight:
return (1.0, 1.0)
}
}
}
let a = Edges.BottomLeft
a.getTuple() // returning (0, 1)
:
原始值可以是字符串、字符或任何整数或浮点数类型
但有一种替代方案适合您:
enum Edges {
case TopLeft
case TopRight
case BottomLeft
case BottomRight
func getTuple() -> (Double, Double) {
switch self {
case .TopLeft:
return (0.0, 0.0)
case .TopRight:
return (1.0, 0.0)
case .BottomLeft:
return (0.0, 1.0)
case .BottomRight:
return (1.0, 1.0)
}
}
}
let a = Edges.BottomLeft
a.getTuple() // returning (0, 1)
元组不能是枚举的原始值类型。发件人: 原始值可以是字符串、字符或任何整数或浮点数类型 不过,您可以创建一个自定义getter:
enum Edges {
case TopLeft, TopRight, BottomLeft, BottomRight
var rawValue: (Double, Double) {
switch self {
case .TopLeft: return (0, 0)
case .TopRight: return (1, 0)
case .BottomLeft: return (0, 1)
case .BottomRight: return (1, 1)
}
}
}
元组不能是枚举的原始值类型。发件人: 原始值可以是字符串、字符或任何整数或浮点数类型 不过,您可以创建一个自定义getter:
enum Edges {
case TopLeft, TopRight, BottomLeft, BottomRight
var rawValue: (Double, Double) {
switch self {
case .TopLeft: return (0, 0)
case .TopRight: return (1, 0)
case .BottomLeft: return (0, 1)
case .BottomRight: return (1, 1)
}
}
}
谢谢你,这段代码有效。但您能否解释一下,每个原始值在其枚举声明中必须是唯一的。@这意味着您不能使用相同的原始值创建两个不同的枚举项,例如
case toplight=1、case toplight=1、case BottomLeft=3,案例BottomRight=4
是不允许的,因为翻倍的1
。但我的数据与你的数据相同,这是否意味着我必须在之前申报案例?@Alexander不,不,一切都很好,我的答案就是这样。我把它包括进来只是为了完成。很抱歉让你有点困惑。这只意味着,如果为某个枚举定义了自定义原始值,则在该枚举内不得两次使用同一原始值。在您的情况下,我们甚至不使用rawValues,因此已经安全了。谢谢您,这段代码可以正常工作。但您能否解释一下,每个原始值在其枚举声明中必须是唯一的。@这意味着您不能使用相同的原始值创建两个不同的枚举项,例如case toplight=1、case toplight=1、case BottomLeft=3,案例BottomRight=4
是不允许的,因为翻倍的1
。但我的数据与你的数据相同,这是否意味着我必须在之前申报案例?@Alexander不,不,一切都很好,我的答案就是这样。我把它包括进来只是为了完成。很抱歉让你有点困惑。这只意味着,如果为某个枚举定义了自定义原始值,则在该枚举内不得两次使用同一原始值。在您的情况下,我们甚至不使用原始值,因此已经安全了。