使用 NSCoding 编码枚举
Encode enum with NSCoding
我正在我的库中实现 NSCoding,但我需要序列化一个枚举变量,我无法将它传递给采用 AnyObject?
的函数。在 Swift 中如何完成?这是我的枚举:
enum ServerType {
case PC
case PE
}
此外,toRaw()
和 fromRaw()
对于 ServerType
不存在。我唯一可以访问的 属性 是 hashValue
,没有我可以访问的方法。
将您的代码更改为
enum ServerType : String {
case PC
case PE
}
您应该可以使用 rawValue
参数。
这类似于@Bennett 的回答,但您可以将它与 NSNumber
一起使用,如下所示:
enum ServerType: UInt {
case PC
case PE
}
let someType: ServerType = .PE
NSNumber(value: someType.rawValue) // 1
我正在我的库中实现 NSCoding,但我需要序列化一个枚举变量,我无法将它传递给采用 AnyObject?
的函数。在 Swift 中如何完成?这是我的枚举:
enum ServerType {
case PC
case PE
}
此外,toRaw()
和 fromRaw()
对于 ServerType
不存在。我唯一可以访问的 属性 是 hashValue
,没有我可以访问的方法。
将您的代码更改为
enum ServerType : String {
case PC
case PE
}
您应该可以使用 rawValue
参数。
这类似于@Bennett 的回答,但您可以将它与 NSNumber
一起使用,如下所示:
enum ServerType: UInt {
case PC
case PE
}
let someType: ServerType = .PE
NSNumber(value: someType.rawValue) // 1