Search code examples
swiftswift-protocolsdecodable

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


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

Solution

  • [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.