Monday, January 8, 2018

Conditional Conformance in the Standard Library

Ben Cohen:

The most noticeable benefit of conditional conformance is the ability for types that store other types, like Array or Optional, to conform to the Equatable protocol. This is the protocol that guarantees you can use == between two instances of a type.


Having equatable elements gives collections other helper functions for tasks like searching[…]


This approach also works for Codable. If you try and encode an array of non-codable types, you’ll now get a compile-time error instead of the runtime trap you used to get.


If the collection we’re splitting is bidirectional, we ought to be able to make our splitting wrapper bidirectional too. In Swift 4.0, the way to do this was pretty clunky. You had to add a whole new type, LazySplitBidirectionalCollection, which required Base: BidirectionalCollection and implemented BidirectionalCollection. Then, you overloaded the split method to return it where Base: BidirectionalCollection.

Now, with conditional conformance, we have a much simpler solution: just make LazySplitCollection conform to BidirectionalCollection when its base does.

1 Comment RSS · Twitter

[…] Previously: Conditional Conformance in the Standard Library. […]

Leave a Comment