Swift的编码/解码枚举(Xcode 6.1)



我有

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
    }

对其进行编码/解码的最佳方式是什么?

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

func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeInteger(priority.rawValue, forKey: "priority")
}
required init(coder aDecoder: NSCoder) {
    priority = Priority(rawValue: aDecoder.decodeIntegerForKey("priority"))
}

最新更新