Wednesday, December 20, 2017

Patterns for Working With Associated Types

Benedikt Terhechte:

The first solution for the archetypical problem is also a really simple one. Instead of enforcing Equatable on your custom protocol, you can simply require your full fledged, final, types to conform to the Equatable protocol instead of your custom protocol.

[…]

As you can see in the example above, using Self as a method parameter or using Self as a property type automatically introduces an associated type (like we saw with Equatable, earlier).

The most helpful note here is that once you use a method instead of a property in order to return something of type Self you will not opt in to an associated 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 the associated 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. […]

Leave a Comment