3

Let's say I have the following protocol:

protocol Driver {
    associatedtype Car
}

And than a protocol inheriting from Driver, explicitly setting Car to be of type RaceCar.

protocol RacingDriver: Driver {
    typealias Car = RaceCar
}

Why do I still get the error

protocol 'RacingDriver' can only be used as a generic constraint because it has Self or associated type requirements

when doing var driver: RacingDriver ?

Background story:

Essentially what I would like to have is a variable which can be of any type conforming to Driver, as long as that type has Car defined to be a RaceCar.

Example:

protocol Driver {
    associatedtype Car
}

protocol RacingDriver: Driver {
    typealias Car = RaceCar
}

struct NascarDriver: RacingDriver {}
struct IndyDriver: RacingDriver {}

struct NormalDriver: Driver {}

var racingDriver: RacingDriver // This could be either a NascarDriver or IndyDriver but not a NormalDriver!

How could I achieve this?

Is there a way around this other than type-erasure?

I would like to avoid subclassing from a RacingDriver base class.

Thanks in advance!

Balázs Vincze
  • 3,550
  • 5
  • 29
  • 60
  • 1
    Possible duplicate of [Protocol can only be used as a generic constraint because it has Self or associatedType requirements](https://stackoverflow.com/questions/36348061/protocol-can-only-be-used-as-a-generic-constraint-because-it-has-self-or-associa). For a solution, you should look into _type erasure_, which also has been discussed extensively [here on SO](https://stackoverflow.com/search?q=%5Bswift%5D+type+erasure). [This](http://robnapier.net/erasure) blog post explaining type erasure can also prove useful. – Dávid Pásztor Apr 20 '18 at 13:00
  • Please see my edited answer! But I guess the answer is a NO. – Balázs Vincze Apr 20 '18 at 13:03
  • AFAIK until Swift will have generic protocols (which was deemed unlikely in the [Generics Manifesto](https://github.com/apple/swift/blob/master/docs/GenericsManifesto.md#conditional-conformances-)), the only solution for using a protocol with associated types as a concrete type is through type erasure. – Dávid Pásztor Apr 20 '18 at 13:10

0 Answers0