0

i have 2 main parts in my app infrastructure.

NetworkingManager
NetworkRequest

My goal is to have the request hold its Codable Type so when networking is done the Manager layer can instantiate new instance with the correct type by using

decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable

so my NetworkRequest look like so

class NetworkRequest {
  var objectClass:Codable.Type
}

lets say i have a Person class which conforms to Codable

class Person : Codable {
 var name:String?
}

now i need to assign the type into the request like so (in an ugly way to get to the point here)

let request = NetworkingRequest()
request.objectClass = Person.self

now when i want the NetworkingManager to decode the response i use it like so:

JSONDecoder().decode(type:request.objectClass, data:dataFromService)

the problem is when i do so i get this error:

Cannot invoke decode with an argument list of type (Decodable.Type, from: Data). Expected an argument list of type (T.Type, from: Data).

any help would be appreciated

a.masri
  • 2,439
  • 1
  • 14
  • 32
orthehelper
  • 4,009
  • 10
  • 40
  • 67

3 Answers3

1

Try something like this:

class NetworkRequest<T: Codable> {
    var objectClass: T.Type

    init(objectClass: T.Type) {
        self.objectClass = objectClass
    }
}
cocavo
  • 163
  • 8
1

Does marking NetworkRequest as a genric <T: Codeable> do what you need?

class NetworkRequest<T: Codable> {
    var objectClass: T.Type
}

Then initing and calling like

let request = NetworkRequest<Person>()
request.objectClass = Person.self

And calling

try JSONDecoder().decode(request.objectClass, from: dataFromService)
mmr118
  • 496
  • 4
  • 14
  • Im trying to wrap my networking manager so it can handle generic requests. it has a func doNetworking(request:NetworkRequest){ } but when i do so i must provide explicit type, by doing so i can use the generic type – orthehelper Sep 17 '18 at 06:12
1
class NetworkRequest<T: Codable> {
    var objectClass: T.Type!

    init(objectClass : T.Type) {
        self.objectClass = objectClass
    }

}

class Person : Codable {
    var name:String?
}

let request = NetworkRequest<Person>(objectClass: Person.self)

let response : Dictionary<String,Any> = ["name":"test"]
let data : Data = try! JSONSerialization.data(withJSONObject: response,options: [])

do {
    let person = try JSONDecoder().decode(request.objectClass, from: data)
    print(person.name ?? "--")
} catch {
    print(error)
}
Pratik Sodha
  • 3,679
  • 2
  • 19
  • 38