(August)
At WWDC 2018, in a very influential session titled (Protocol-Oriented Programming in Swift
To illustrate the point, Dave described a protocol-oriented approach to a primitive drawing app. The example worked from a few of primitive shapes:
(Polygon) : (Drawable) {
var corners : [CGPoint] = } struct Circle : (Drawable) {
var center : (CGPoint) var radius : (CGFloat) } struct Diagram : (Drawable) {
var elements : = } These are value types. That eliminates many of the problems of an object-oriented approach:
Instances aren't shared implicitly
The reference semantics of objects add complexity when passing objects around. Changing a property of an object in one place can affect other code that has access to that object. Concurrency requires locking, which adds tons of complexity.
No problems from inheritance
Reusing code via inheritance is fragile. Inheritance also couples interfaces to implementations, which makes reuse more difficult. This is its own topic, but even OO programmers will tell you to prefer “composition over inheritance”.
No imprecise type relationships
With subclasses, it's difficult to precisely identify types. e.g. with NSObject.isEqual () , you must be careful to only compare against compatible types. Protocols work with generics to precisely identify types.
To handle the actual drawing, a Renderer protocol was added that describes the primitive drawing operations:
protocol Renderer { func move ( to p
: CGPoint ) func line ( to p
: CGPoint ) func arc ( at center
: CGPoint , radius