iOS:如何使用协议类型变量的模型 class 可解码

iOS: How to use decodable for a model class with variable of type a protocol

问题:有一个模型class符合Decodable,这个模型有一个someProtocol类型的变量。但是编译器报错,

编译错误

Type 'MyModel' does not conform to protocol 'Decodable'
Protocol requires initializer 'init(from:)' with type 'Decodable'
Cannot automatically synthesize 'Decodable' because 'SomeProtocol' does not conform to 
'Decodable'

代码片段

class MyModel: Decodable {
var name: String?
var employee: SomeProtocol?

enum CodingKeys: String, CodingKey {
    case name
    case employee
}

} // Enf of class MyModel

protocol SomeProtocol {
 var employeeName: String ? { get }
}

[已解决]

你好, 所以我想这个问题是有效的,经过一番搜索,我能够解决。

MyModel class 不能有协议类型,应该有一个继承协议的具体类型 class。对象现在也与嵌套的其他模型对象一起解码。

更正以上代码

class MyModel: Decodable {
var name: String?
var employee: OtherModel?

enum CodingKeys: String, CodingKey {
case name = "DepartmentName"
case employee
}

} // End of class MyModel

class OtherModel: SomeProtocol {
var employeeName: String?
}

protocol SomeProtocol: Decodable {
 var employeeName: String? { get }
}

注意:
不需要初始化(来自解码器:Decoder) 在这种情况下。