Sunday, December 20, 2015

Swift Standard Library Protocols

Greg Heo (via Natasha Murashev):

First up we got the “Can do” protocols. And these describe things that the type can do or have done to it. And they also end in the -able syntax which makes them easy to spot as you’re browsing through the headers. Here’s a first example: A type that conforms to the Hashable protocol, means that you can hash the thing down to an int.


Next step are the “Is a” protocols, and these describe what kind of thing the type is. In contrast to the “can do” protocols, these are more based on identity. That means conforming to multiple protocols of this kind feels the closest to something like multiple inheritance in Swift. You can identify these protocols in the standard library because they end in the word “-type”. And this is fully half of the standard library, something like 35 or so of those 54 are of this kind. Let’s look at an example. CollectionType is a good one. Not surprisingly Array, Dictionary, and Set conform to CollectionType. Maybe slightly more surprisingly, things like Ranges and String views.


Finally we have the “Can be” types. Rather than just an alternate view of the same thing, as we have already seen, these are more about straight on conversion. Changing from type X over to type Y. And these ones end in the word “-Convertible”. So that means that the type can either be converted from or converted to something else.

Comments RSS · Twitter

Leave a Comment