swift5decodable

Getting errors while using decodable extension in different module in Swift


I am facing issues while using init(from decoder: Decoder) in Model extension in different module.

I have model in Module 1 as below

public struct LabelModel {
    public var value: String?
}

And I have decodable extension in module 2

extension LabelModel: Decodable {
    enum CodingKeys: String, CodingKey {
        case value
    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        value = try container.decodeIfPresent(String.self, forKey: .value) // error - 'self' used before 'self.init' call or assignment to 'self'
    } // error - 'self.init' isn't called on all paths before returning from initializer
}

I am facing 2 errors while adding model extension with decodable in different module. Any suggestion will be helpful for me. Thanks in advance.


Solution

    1. put the decoded value into a local let,

    2. create a LabelModel with that value as you normally would

    3. set self to that LabelModel

       public init(from decoder: Decoder) throws {
           let container = try decoder.container(keyedBy: CodingKeys.self)
           let value = try container.decodeIfPresent(String.self, forKey: .value)
           // let someOtherProperty = ...
           // other properties (if any)...
      
           // assuming LabelModel has such a public initialiser...
           var label = LabelModel()
           // if it doesn't have a public initialiser, then this is not possible
           label.value = value
           // label.someOtherProperty = someOtherProperty
           // other properties (if any)...
      
           self = label
       }
      

      If LabelModel has an initialiser that takes a value directly, you can just call that initialiser.

       let value = ...
       let label = LabelModel(value: value)
       self = label