0

In Swift, if I declare a class based on generic type:

class BasicRequest<T>{
}

class StartRequest: BasicRequest<BasicPayload> {
}

And then try to use generic method:

class SocketClient {

  public func send(request: BasicRequest<Any>){
  }
}

It does not compile:

SocketClient.shared.send(request: StartRequest()) 

with message

Cannot convert value of type 'StartRequest' to expected argument type 'BasicRequest'

Why actually? The type info should be available across the inheritance chain.

Arnie Schwarzvogel
  • 955
  • 1
  • 13
  • 25

1 Answers1

2

Generics are invariant in Swift, which in your case means that BasicRequest<Any> is not compatible with BasicRequest<BasicPayload>, even if BasicPayload is compatible with Any. This is how invariants work, there's little you can do in this direction.

What you can do, is to make send generic, thus allowing any kind of BasicRequest instances to be passed:

public func send<T>(request: BasicRequest<T>){
}
Cristik
  • 30,989
  • 25
  • 91
  • 127