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

7

I have

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
    }

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

类似问题:https://dev59.com/iV8d5IYBdhLWcg3w41gp。 - Martin R
1个回答

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"))
}

1
感谢您为6.1版本添加更新。 - jpittman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接