Patterns for Working With Associated Types
The first solution for the archetypical problem is also a really simple one. Instead of enforcing
Equatableon your customprotocol, you can simply require your full fledged, final, types to conform to theEquatableprotocol instead of your custom protocol.[…]
As you can see in the example above, using
Selfas a method parameter or usingSelfas a property type automatically introduces anassociated type(like we saw withEquatable, earlier).The most helpful note here is that once you use a
methodinstead of apropertyin order to return something of typeSelfyou will not opt in to anassociated type[…][…]
The idea here is that you define two protocols that share common methods. Only one of those protocols contains
associated types, the other does not. Your types conform to both protocols. This means that you can use the normal protocol as a type for all situations. If you, then, need to use the parts of the type that only affect theassociated type, you can do so by means of a runtime cast.
1 Comment RSS · Twitter
[…] Previously: Swift Protocols With Associated Types, Swift Type Erasure, Patterns for Working With Associated Types. […]