-2

I have a question about Protocol with associated type, why I can not make the protocol a type of my instance for example: enter image description here

I know I can use Type Erasure to fix the issue, but why protocol with an associated type does not like to be a type of an instance, and if you will say because the associated type is also used as a constraint, well I want to implement the properties inside the protocol not inside its extensions since protocol extensions has the power to control who can access its properties, why we still have this issue.

Thank you.

Zyz
  • 123
  • 1
  • 9
  • Does this answer your question? [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) – nayem Dec 13 '19 at 04:59
  • it made me even more confused – Zyz Dec 13 '19 at 05:38

1 Answers1

1

There are lots of articles and answers (like this one) out there describing why but in summary, It needs associatedtype. Variables can not have an associatedtype. So alongside with Type Erasure method (that you don't want), you can simply make it opaque with adding some keyword to the type:

var objectA: some ProtocolA = A()
Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278