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

时间:2014-10-18 08:10:23

标签: ios swift enums

我有

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
    }

对此进行编码/解码的最佳方法是什么?

1 个答案:

答案 0 :(得分:17)

Priority.init(rawValue:)应该有用。

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

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