RawRepresentable类型的泛型似乎被误解为self

时间:2016-02-02 13:38:34

标签: swift generics rawrepresentable

要将NSCoding与Swift的枚举类型一起使用,我在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支持的枚举,但是当我尝试解码先前编码的枚举时,如下所示:

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()

1 个答案:

答案 0 :(得分:1)

问题在于

guard let tmp = aDecoder.decodeEnumForKey("myKey") as? MyEnum else { return nil }

编译器无法推断

的通用占位符
func decodeEnumForKey<Enum: ...>(key: String) -> Enum?

MyEnum,您必须将结果转换为MyEnum?

guard let tmp = aDecoder.decodeEnumForKey("myKey") as MyEnum? else { return nil }

以便从调用上下文中将返回类型推断为MyEnum?