【问题标题】:Swift integer type cast to enumSwift整数类型转换为枚举
【发布时间】:2015-01-25 22:25:01
【问题描述】:

我有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'。在这里尝试了许多排列。但无法弄清楚。

【问题讨论】:

    标签: ios swift enums


    【解决方案1】:

    你需要指定枚举的原始类型

    enum OP_CODE: Int {
        case addition, substraction, multiplication, division
    }
    

    addition 的原始值将是 0substraction1,依此类推。

    然后你就可以了

    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 fromRaw() 而不是可失败的初始化程序:

    let code = OP_CODE.fromRaw(indexPath.row)
    

    【讨论】:

    • 试过了。遇到错误OP_CODE cannot be constructed it has no accessible initializers- 请简要介绍一下。
    • 我可能打错了,现在试试
    • 我尝试了代码,它在我这边工作,你在哪个版本的 Xcode 上?
    • Xcode - 版本 6.0.1 (6A317) 和 OS X Yosemite 版本 10.10
    • 那是旧版本,这种情况下你可以使用OP_CODE.fromRaw(indexPath.row),但你真的应该升级到6.1
    【解决方案2】:

    您可以在枚举中使用raw values

    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 的答案和相关的 cmets。

    【讨论】:

    • 感谢您的快速帮助。
    猜你喜欢
    • 1970-01-01
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    相关资源
    最近更新 更多