0

This is my function:

func get<T: Decodable>(type: T.Type, subclass: T){}

I have an array of random objects. The objects that conform to the protocol Decodable should be able to call this function. This is what I mean:

class MasterClass{
    func get<T: Decodable>(type: T.Type, subclass: T){}
}

class A: MasterClass, Decodable{}

class B: MasterClass{}

func x(){
    let array: [MasterClass] = [A(), B()]
    for obj in array{
       if let conformer = obj as? Decodable{
           obj.get(type: type(of: conformer), subclass: conformer)
           //doesn't work
       }
   }
}

I do not get this to work, but I can not understand why.

Cannot invoke 'get' with an argument list of type '(type: Decodable.Type, subclass: Decodable)'

J. Doe
  • 12,159
  • 9
  • 60
  • 114
  • Protocols don't conform to themselves: https://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself - you need to pass a concrete type to `get` – Cristik Mar 19 '18 at 21:50
  • @Cristik so it is not possible to say the to compiler that obj surely conforms to Decodable? – J. Doe Mar 19 '18 at 21:58
  • That's very possible, the method declaration is fine, the problem is how you call it: T needs to be a concrete type so that the compiler knows how to pass it to the called method – Cristik Mar 19 '18 at 21:59
  • @Cristik How would I do that? I translated it to Java and I got an answer there: https://stackoverflow.com/questions/49382457/call-generic-method-with-interface-constraints-on-objects-who-may-implement-that – J. Doe Mar 20 '18 at 11:10
  • It might not be possible with your current setup. What are you trying to achieve with this, maybe we can find another way – Cristik Mar 20 '18 at 12:51

0 Answers0