RawRepresentable 类型的泛型似乎被误解为自我

Generic of type RawRepresentable is misinterpreted as self it seems

为了将 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()

问题是

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 }

以便从调用上下文推断 return 类型为 MyEnum?