[英]Generic of type RawRepresentable is misinterpreted as self it seems
To use NSCoding
with Swift's Enum type I made an extension on NSCoder
: 要将
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)
}
}
The encodeEnum
method works fine for a String
-backed Enum, but when I try to decode the prior encoded Enum like so: encodeEnum
方法对于由String
支持的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)
}
}
I get an error on aDecoder.decodeEnumForKey("myKey")
: 我在
aDecoder.decodeEnumForKey("myKey")
上收到错误:
Value of type `NSCoder` has no member `RawValue`
I'm pretty sure it has something to do with the generic and the condition that Enum.RawValue == String
. 我很确定它与泛型和
Enum.RawValue == String
的条件有关。 But I do not understand while it's not working, but works for encodeEnum()
. 但是我不明白虽然它不起作用,但适用于
encodeEnum()
。
The problem is that in 问题是
guard let tmp = aDecoder.decodeEnumForKey("myKey") as? MyEnum else { return nil }
the compiler cannot infer the generic placeholder of 编译器无法推断出
func decodeEnumForKey<Enum: ...>(key: String) -> Enum?
to be MyEnum
, you have to cast the result to MyEnum?
成为
MyEnum
,您必须将结果转换为MyEnum?
instead: 代替:
guard let tmp = aDecoder.decodeEnumForKey("myKey") as MyEnum? else { return nil }
so that the return type is inferred as MyEnum?
以便将返回类型推断为
MyEnum?
from the calling context. 从调用上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.