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

前端之家收集整理的这篇文章主要介绍了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)
原文链接:https://www.f2er.com/iOS/335171.html

猜你在找的iOS相关文章