【问题标题】:Encode/Decode enum for Swift (Xcode 6.1) [duplicate]为 Swift 编码/解码枚举(Xcode 6.1)[重复]
【发布时间】:2014-12-13 18:47:44
【问题描述】:

我有

var priority : Priority! = Priority.defaultPriority

func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeInteger(priority.toRaw(), forKey: "priority") //toRaw may not yield the result I am expecting
    }

    required init(coder aDecoder: NSCoder) {
        priority = aDecoder.decodeIntegerForKey("priority") //complaining about conflicting types
    }

枚举如下:

enum Priority : Int {
        case defaultPriority = 0
        case lowPriority = 1
        case mediumPriority = 2
        case highPriority = 3
    }

编码/解码的最佳方法是什么?

【问题讨论】:

标签: ios swift enums


【解决方案1】:

Priority.init(rawValue:) 应该可以工作。

func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeInteger(priority.rawValue, forKey: "priority")
}

required init(coder aDecoder: NSCoder) {
    priority = Priority(rawValue: aDecoder.decodeIntegerForKey("priority"))
}

【讨论】:

  • 感谢您为 6.1 添加更新。
猜你喜欢
  • 2019-01-06
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 2018-11-17
相关资源
最近更新 更多