[英]Enumeration with raw values
為什么我不能用這樣的原始值定義枚舉?
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)
}
元組不能是枚舉的原始值類型。 來自Swift編程語言 :
原始值可以是字符串,字符或任何整數或浮點數類型。
您可以通過以下方式創建自定義獲取器:
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)
}
}
}
因為 :
原始值可以是字符串,字符或任何整數或浮點數類型。
但是,還有另一種解決方案:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.