Conditional Conformance in the Standard Library
The most noticeable benefit of conditional conformance is the ability for types that store other types, like
Array
orOptional
, to conform to theEquatable
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 requiredBase: BidirectionalCollection
and implementedBidirectionalCollection
. Then, you overloaded thesplit
method to return itwhere Base: BidirectionalCollection
.Now, with conditional conformance, we have a much simpler solution: just make
LazySplitCollection
conform toBidirectionalCollection
when its base does.