0

I have a problem with generic func for different classes under one Protocol:

public typealias Handler = (Result<Object, JSONError>) -> Void

private func fetchData<T>(endPoint: String, 
                          type: T.Type = T.self, 
                          completion: @escaping (Handler)) 
                          where T: Protocol { 
        completion(.success(fetchedData.object)) 
}

protocol Protocol: JSONDecodable {
    var object: Object { get }
}

class First: Protocol { 
    var object = Object()
    required init(json: JSON) throws {
             object = Object()
    }
}

I want to use it like that:

var endPoint: String = ""
var metaType: Protocol.Type
switch f.name {
case .First:
      endPoint = "/accounts/" + ""
      metaType = First.self
}
fetchData(endPoint: endPoint, type: metaType) { (result) in
}

Errors: Cannot convert value of type 'Protocol.Type' to expected argument type 'T.Type'; Generic parameter 'T' could not be inferred

Could you advise me how to approach this problem? Many thanks in advance!

Sergey
  • 1
  • 1
  • `metaType` must be a concrete type, not a protocol. The declaration as protocol type breaks the functionality. – vadian May 25 '20 at 09:01
  • Does [this](https://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself) answer your question? – Sweeper May 25 '20 at 09:04
  • @vadian If I declare `metaType` as `First.self` in next switch case I won’t be able to set it as `Second.self`. So the only way to make it work somehow is to call function in each case with a certain class type in it, but it repeats 10-15 times already (and will repeat more in the future) with copy past code with different passing class types. – Sergey May 25 '20 at 14:28
  • @vadian Basically, I have protocol, so all classes that conform to it have default `object` implementation for free as protocol stubs and different `init(json: JSON)` which return this `object`. I want to avoid this massive code duplication. Function must be called only after switch statement defines `class type` and `endpoint` for it. – Sergey May 25 '20 at 14:28
  • @Sweeper As far as I'm concerned, it does't. – Sergey May 25 '20 at 14:44
  • To fulfill the requirement to pass a concrete type declare a function with a generic parameter constrained to the protocol. A protocol as common type is the wrong approach. – vadian May 25 '20 at 16:09

0 Answers0