首页 > 解决方案 > 类引用可编码协议是不可编码的

问题描述

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

/* 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()
    }
 }

标签: swiftencodingdecodingswift-protocols

解决方案


这就是你修复它的方法。

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

并以这种方式使用它

let a = AnotherClass<MyClass>()

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


推荐阅读