为了使用NSCoding
Swift 的 Enum 类型,我做了一个扩展NSCoder
:
extension NSCoder {
func encodeEnum<Enum: RawRepresentable where Enum.RawValue == String>(value: Enum, forKey key: String) {
self.encodeObject(value.rawValue, forKey: key)
}
func decodeEnumForKey<Enum: RawRepresentable where Enum.RawValue == String>(key: String) -> Enum? {
guard let returnValue = self.decodeObjectForKey(key) as? String else { return nil }
return Enum(rawValue: returnValue)
}
}
该encodeEnum
方法适用于String
-backed Enum,但是当我尝试像这样解码先前编码的 Enum 时:
enum MyEnum: String { case Something, Other }
class MyEnumClass: NSObject, NSCoding {
let myEnum: MyEnum
init(myEnum: MyEnum) {
self.myEnum = myEnum
}
required convenience init?(coder aDecoder: NSCoder) {
guard let tmp = aDecoder.decodeEnumForKey("myKey") as? MyEnum else { return nil }
self.init(myEnum: tmp)
}
}
我收到一个错误aDecoder.decodeEnumForKey("myKey")
:
Value of type `NSCoder` has no member `RawValue`
我很确定它与泛型和条件有关Enum.RawValue == String
。但我不明白,虽然它不起作用,但适用于encodeEnum()
.