我有一个enum
声明。
enum OP_CODE {
case addition
case substraction
case multiplication
case division
}
并在一种方法中使用它:
func performOperation(operation: OP_CODE) {
}
我们都知道我们怎么能正常称呼它
self.performOperation(OP_CODE.addition)
但是,如果我必须在整数值不可预测的某个委托中调用它,我该如何调用它?
例如:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.delegate.performOperation(indexPath.row)
}
在这里,编译器抛出一个错误Int is not convertible to 'OP_CODE'
。我尝试了很多排列,但一直无法弄清楚。
需要指定枚举的原始类型
enum OP_CODE: Int {
case addition, substraction, multiplication, division
}
addition
的原始值为 0
、 substraction
1
等。
然后你可以做
if let code = OP_CODE(rawValue: indexPath.row) {
self.delegate.performOperation(code)
} else {
// invalid code
}
更多信息在这里: https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Enumerations.html#//apple_ref/doc/uid/TP40014097-CH12-XID_222
对于较旧的 SWIFT 版本
如果您使用的是旧版本的 swift,原始枚举的工作方式会有所不同。在 Xcode <6.1 中,您必须使用 fromRaw()
而不是可失败的初始值设定项:
let code = OP_CODE.fromRaw(indexPath.row)
您可以在枚举中使用原始值:
enum OP_CODE : Int{
case addition = 0
case substraction = 1
case multiplication = 2
case division = 3
}
并使用将原始值作为输入的可故障初始值设定项:
let code = OP_CODE(rawValue: 2) // code == .multiplication
请注意,code
是可选的,因为如果原始值未映射到有效的枚举,则初始值设定项将返回 nil。
在您的情况下:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let code = OP_CODE(rawValue: indexPath.row)
if let code = code {
self.delegate.performOperation(code)
}
}
此外,给定枚举的实例,您可以使用 rawValue
属性获取关联的原始值。
注意:枚举在 Xcode 6.1 中发生了一些变化 - 如果您使用的是以前的版本,请阅读 @GabrielePetronella 的答案和相关评论。