27 Mar 2016

Protocol-Oriented Programming in Swift

Swift, Apple’s new programming language, has an interesting feature called protocol-oriented programming. When Apple says “protocol”, they mean the equivalent of an interface in Java. Rather than saying that a class implements an interface, we say that a class conforms to a protocol. Or to multiple protocols, as in in Java. A protocol can also inherit from another protocol, again like Java.

Further, a protocol can have a default implementation, again similar to Java 8. This lets you evolve a protocol by adding new methods to it, without breaking all classes that conform to it.

Where Swift goes beyond Java is that you can retrofit a class to implement a protocol, even if it’s a class from a library you don’t have the source code to. So, you can add new methods to a pre-existing class, and then declare that the class conforms to the protocol [1].

Swift protocols can also specify that the class has a certain property. Since properties are just syntactic sugar for a getter and a setter, when a protocol declares a property, it’s just declaring a getter and a setter.

And with generic types, you can define an implementation that works for all parameterised types. Imagine defining a protocol InSortedOrder that returns the elements of a collection in sorted order. You can retrofit that to all collections, and add a default implementation that iterates over the items, sorts them and then returns the sorted items. This default implementation can be generic so that it works for collections of all types.

It’s interesting to see Swift build on Java interfaces and take them one step further.

[1] This is still not as seamless as Go where a class is considered to automatically implement an interface if it implements all the methods declared in the interface. On the other hand, if a class in Go doesn’t implement the methods you need, you can’t retrofit it via an extension.

No comments:

Post a Comment