-1

Hi we are using codeble in our Api management layer, we are trying to set up models with codables and decodables,

in one case we have Error in our response model, how can we handle that

here is the sample code

 struct Address : Codable {

        var street: String
        var zip: String
        var city: String
        var error: Error

        private enum CodingKeys : String, CodingKey {
            case street, zip = "zip_code", city, state
        }
    }

we are getting below error

Cannot automatically synthesize 'Encodable' because 'Error' does not conform to 'Encodable'

How can we handle error type in codables ?

manishsharma93
  • 1,039
  • 1
  • 11
  • 26
Afsara
  • 1,411
  • 3
  • 13
  • 31
  • The error means what it says. `Error` is a protocol. You cannot encode/decode protocols so you have to write a custom `init` / `encode` methods to handle the type. – vadian Jun 07 '19 at 08:52
  • You probably shouldn't have an `Error` in your struct. The function that retrieves the `Address` should return a `Result
    `
    – Paulw11 Jun 07 '19 at 09:12
  • Try formatting your data from https://www.json4swift.com/ for codables. – manishsharma93 Jun 07 '19 at 10:28

1 Answers1

0

Why do you need an Error property in this struct ?

You can send your Address model if api response is success, you can send Error model if api response is failure, also you can create your own error model inherited from the Error.

kirami
  • 273
  • 1
  • 4