swift - 我如何编码(使用 NSCoding)没有 rawValue 的枚举?

标签 swift encoding enums swift3 nscoding

我试图使我的类符合 NSCoding,但遇到了问题,因为它的属性之一是枚举,如下所示:

enum Direction {
    case north
    case south
}

如果枚举是可编码的,我可以这样做:

class MyClass: NSObject, NSCoding {
    var direction: Direction!
    required init(coder aDecoder: NSCoder) {
        direction = aDecoder.decodeObject(forKey: "direction") as! Direction
    }
    func encode(with aCoder: NSCoder) {
        aCoder.encode(direction, forKey: "direction")
    }
}

但枚举不可编码,因此 encode() 会抛出错误。

How do I encode enum using NSCoder in swift?”的答案建议对枚举的 rawValue 进行编码,然后从另一端的 rawValue 对其进行初始化。但在这种情况下,Direction 没有 rawValue!

它确实有一个 hashValue,这看起来很有希望。我可以毫无问题地对其 hashValue 进行编码,并在另一端解码回 Int。但是似乎没有办法从 hashValue 初始化枚举,所以我无法将它转回 Direction

我如何编码和解码无值(value)的枚举?

最佳答案

Swift 4 中的新功能,枚举可编码的。但是,它必须具有原始值。但是,您无需额外代码即可轻松完成:

enum Direction : String, Codable {
    case north
    case south
}

要使您的 Codable 枚举与 NSCoding 类 MyClass 一起工作,请像这样实现您的 init(coder:)encode(with:):

class MyClass: NSObject, NSCoding {
    var direction: Direction!
    required init(coder aDecoder: NSCoder) {
        direction = (aDecoder as! NSKeyedUnarchiver).decodeDecodable(Direction.self, forKey: "direction")
    }
    func encode(with aCoder: NSCoder) {
        try? (aCoder as! NSKeyedArchiver).encodeEncodable(direction, forKey: "direction")
    }
}

关于swift - 我如何编码(使用 NSCoding)没有 rawValue 的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43512146/

相关文章:

ios - 将框架嵌入到另一个框架中

swift - 是否可以在结构复制期间排除某些属性(如类类型)被复制?

python - 使用 BeautifulSoup 在 python 中进行编码

http - 为什么 HTTP 响应负载在 Wireshark tcp 流中显示为乱码?

java - 如何更改android studio中的编码

MySQL 根据 ENUM 值进行选择

java - JComboBox 填充枚举变量值

ios - 错误:“预期返回Int的函数中缺少返回”

arrays - 如何将字典加载到 UIPickerView

.net - wcf - 更改整数值时枚举是否向后兼容?