我试图使我的类符合 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/