类引用可编码协议是不可编码的



如果我的类 OtherClass 的成员是具有可编码抽象协议的类型,编译器将无法合成该类的编码/解码代码。相反,如果同一成员是符合相同协议的具体类,则编译器将愉快地合成编码/解码代码。我认为第二种情况应该有效,属性 mp 将始终是 MyProtocol 的可编码具体实例,它是可编码的。

/* This works */

protocol MyProtocol : Codable {
    func a(_ n : Int) -> Int
}
class MyClass : MyProtocol {
    let x = 3
    func a( _ n : Int ) -> Int {
        return n * x
    }
}
class AnotherClass : Codable {
    let y = 5
    let mp : MyClass // <---- ACTUAL CLASS
    init() {
        mp = MyClass()
    }
}
/* But this won't work. 
  Compiler error: 
  Type 'AnotherClass' does not conform to protocol 'Decodable'
  Type 'AnotherClass' does not conform to protocol 'Encodable'
*/
protocol MyProtocol : Codable {
    func a(_ n : Int) -> Int
}
class MyClass : MyProtocol {
    let x = 3
    func a( _ n : Int ) -> Int {
        return n * x
    }
}
class AnotherClass : Codable {
    let y = 5
    let mp : MyProtocol // <-------- PROTOCOL
    init() {
        mp = MyClass()
    }
 }

这就是你修复它的方式。

class AnotherClass<T: MyProtocol> : Codable {
    let y = 5
    let mp : T
    init() {
        mp = MyClass() as! T // handle this more gracefully
    }
}

并以这种方式使用它

let a = AnotherClass<MyClass>()

但请考虑在此处阅读此答案。它解释了为什么协议的行为方式如此,并将帮助您更多地了解它们。

最新更新