ios – Swift整数类型转换为枚举

我有枚举声明.
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不能转换为’OP_CODE’.在这里尝试了许多排列.但无法弄明白.

解决方法

您需要指定枚举的原始类型
enum OP_CODE: Int {
    case addition,substraction,multiplication,division
}

添加的原始值为0,减法为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,原始枚举的工作方式会有所不同.在Xcode< 6.1,你必须使用fromRaw()而不是一个可用的初始化器:

let code = OP_CODE.fromRaw(indexPath.row)

以上是来客网为你收集整理的ios – Swift整数类型转换为枚举全部内容,希望文章能够帮你解决ios – Swift整数类型转换为枚举所遇到的程序开发问题。

如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。