简体   繁体   中英

Swift: Protocol With associatedType

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM