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

纵饮孤独 提交于 2020-03-06 11:05:33

问题


Question: There is a model class that conforms to Decodable, this model has a variable of type someProtocol. But compiler gives an error,

Compiler error

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'

Code Snippet

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 }
}

回答1:


[SOLVED]

Hi, So I guess this question was valid and after some searching, I was able to solve.

MyModel class cannot have a protocol type, there should be a concrete type class that inherits protocol. Object is now decoded with nested other model objects too.

Corrected Above code

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 }
}

Note:
Didn't need init(from decoder: Decoder) in this case.



来源:https://stackoverflow.com/questions/60460695/ios-how-to-use-decodable-for-a-model-class-with-variable-of-type-a-protocol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!