0

I've created a network manager that gets a JSON response and converts it in to a Swift object,

protocol HTTPResponse: Codable {
        
}

class UserResponse: HTTPResponse {
   var name: String?
}

let responseObj = try? JSONDecoder().decode(T.self, from: response.data!)

where T is an HTTPResponse decendent

I need to be able to create an 'empty' UserResponse object, an instance where all the class variables are nil

I changed HTTPResponse from protocol to class and added an empty required init() {} to it.

This allows me to invoke T() and get an instance of UserResponse but now JSONDecoder is no longer parsing the JSON, it also creates instances where all variables are nil

How can I achieve the end result where JSONDecoder works well, and I can create stub instances of my HTTPResponse decedent classes?

I'm working with swift 4.2

pawello2222
  • 46,897
  • 22
  • 145
  • 209
Aviran
  • 5,160
  • 7
  • 44
  • 76

1 Answers1

1

You can add the initialiser requirement to the protocol:

protocol HTTPResponse: Codable {
    init()
}

Then, add a required init() { ... } to UserResponse and all the conformers. Each conformer can decide what a "stub" response means for them.

After that T() will work, given that T is a generic parameter with the constraint <T: HTTPResponse>. This might seem strange as you are initialising a protocol. But actually, since protocols don't conform to themselves, T will never be HTTPResponse, and will always be a concrete class that conforms to HTTPResponse.

Sweeper
  • 213,210
  • 22
  • 193
  • 313