Patterns for Working With Associated Types
The first solution for the archetypical problem is also a really simple one. Instead of enforcing
Equatable
on your customprotocol
, you can simply require your full fledged, final, types to conform to theEquatable
protocol instead of your custom protocol.[…]
As you can see in the example above, using
Self
as a method parameter or usingSelf
as a property type automatically introduces anassociated type
(like we saw withEquatable
, earlier).The most helpful note here is that once you use a
method
instead of aproperty
in order to return something of typeSelf
you 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. […]