我有这个枚举:
enum GestureDirection:UInt {
case Up = 1 << 0
case Down = 1 << 1
case Left = 1 << 2
case Right = 1 << 3
}
但在每种情况下,我都会得到错误:
枚举大小写的原始值必须是文本
我不明白。
Swift 1.2,Xcode 6.3.2
发布于 2015-05-19 20:05:17
这是因为1 << 0
不是字面量。您可以使用二进制文字,它是一个文字,并且在那里是允许的:
enum GestureDirection:UInt {
case Up = 0b000
case Down = 0b001
case Left = 0b010
case Right = 0b100
}
枚举仅支持每个numeric-literal
为raw-value-literal
(数字)、string-literal
(字符串)或boolean-literal
(布尔值)的language grammar。
相反,作为一种变通办法,仍然可以很好地指示您正在做什么。
发布于 2015-05-19 20:44:56
(答案已针对Swift 5及更高版本更新。旧版Swift的解决方案可在编辑历史记录中找到。)
对于不是互斥的属性,可以使用struct
并声明符合OptionSet
协议。优点是所有的位操作都是免费的。
您只需定义底层存储类型和预定义的值:
struct GestureDirection : OptionSet {
let rawValue : UInt8
static let top = Self(rawValue: 1 << 0)
static let down = Self(rawValue: 1 << 1)
static let left = Self(rawValue: 1 << 2)
static let right = Self(rawValue: 1 << 3)
}
用法:
// Initialize:
var direction : GestureDirection = [ .top, .right ]
// Test:
if direction.contains(.top) {
// ...
}
// Add an option:
direction.insert(.left)
// Remove an option:
direction.remove(.right)
发布于 2016-10-11 02:50:46
Swift 2.2版本:在我的例子中,我需要转换String Enum值以在可本地化的String中使用。所以在我的枚举中添加了这个方法。
enum DisplayCellTitle: String {
case Clear
func labelTitle() -> String {
switch self {
case .Clear:
return "LBL_CLEAR".localizedWithComment("Clear")
}
}
}
然后像这样使用它:
// Get the localised value of the Cell Label Title
let lblTitle = DisplayCellTitle.labelTitle(cellTitle)()
传入的cellTitle只是这些CellTitle枚举值之一
https://stackoverflow.com/questions/30325058
复制相似问题