Understanding Swift 4 protocols and using them in your apps

NOTE: Learn all about protocol-oriented programming in Swift here, here, and here.

[Download two Xcode 9 playgrounds with full Swift 4 source from GitHub.]

We’re going to talk about “protocols” in the Swift 4 language today. I’ll explain them conceptually, and then we’ll start coding protocols with a simple example. We’ll then create our own versions of the Apple built-in Equatable and Comparable protocols, and apply them to two real-world classes, one for tracking financial securities and one for representing geometric lines/vectors. Finally, we’ll test our geometric “Line” class in a type of Swift playground that supports rendering user interface components (like UIView) live in the simulator. But first, please ponder the layman’s definition of the word “protocol” before moving on:

… The official procedure or system of rules governing affairs of state or diplomatic occasions. …

The accepted or established code of procedure or behaviour in any group, organization, or situation. …

A procedure for carrying out a scientific experiment…

Swift Protocols

Apple’s “The Swift Programming Language (Swift 4.0.3)” documentation states:

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol. …

For me, protocols are one of the most important tools we have to bring some order to the inherent chaos that is software. Protocols give us the ability to require that some — even many — of our classes contain/perform certain minimum or required properties and/or functionality, especially if assigned to base classes in class hierarchies.

Adopting a protocol
Consider the layman’s definition (above) and now the computer science definition of “protocol” together. Then remember my discussion of Swift generics where I made my “Person” class conform to (adopt) the Equatable protocol. You can read that article, but I’ll remind you what I did:

Apple states that, “Custom types state that they adopt a particular protocol by placing the protocol’s name after the type’s name, separated by a colon, as part of their definition.” That’s just what I did:

You can conceptualize a protocol as a contract or promise that you can apply to a class, structure, or enumeration. I have entered my “Person” class into a contract with the Equatable protocol, and the “Person” class promises to fulfill the contract by implementing the methods or member variables that Equatable requires be materialized or fulfilled, i.e., implemented.

The Equatable protocol doesn’t implement anything. It only specifies what methods and/or member variables must be implemented by the class, structure, or enumeration that adopts (conforms to) Equatable. (Some protocols implement functionality through “extensions,” but that is beyond the scope of this discussion.)

Defining a protocol
Protocols are best understood from example code. I’m going to implement my own version of Equatable to show you how protocols work:

Remember that my “IsEqual” protocol doesn’t implement the == and != operators. “IsEqual” requires that adopters of the protocol implement their own == and != operators.

To show you how widely applicable is a protocol like my “IsEqual” (or Equatable), let’s get creative and build a class that will model a position in a financial stock. Each instance of my “StockAtClosing” class represents the value of the number of shares of a particular security on a particular day after the stock market’s closing bell.


Your assignment
I’m not going to explain the domain knowledge particulars of the “StockAtClosing” class. I want you to take the time to understand the purpose of the class, i.e., look up definitions for the member variables “symbol,” “shares,” “price,” and “value.” Find out things like why I marked the timestamp for the stock just when the market closes. Hint, hint 😉 … Look at a daily history of Apple’s stock price.

I am going to discuss how “StockAtClosing” adopts the “IsEqual” protocol.

Custom class adopting a custom protocol
If not familiar with the stock market, have you done your research on financial securities and exchanges? You should…

Before looking at my finished “StockAtClosing” class, what if I had adopted the “IsEqual” protocol without implementing the required == and != operators? I would’ve received Swift compile-time errors — and informative ones:

Here’s my “StockAtClosing” class and some test output:

Adopting multiple protocols
When I first started this article, I got greedy and had thought about manually creating a protocol that mirrored both Apple’s Equatable and Comparable protocols:

I realized that I should divide and conquer and make my code as flexible as possible. Why not? Apple states that multiple protocols can be adopted by a class, structure, or enumeration, as we’ll see below. Here are the two protocols I came up with:

Remember your algorithms
An important skill you need to hone is the development of algorithms, and translating them into code. I guarantee that one day somebody is going to give you a verbal description of some complex process and ask you to encode it. There’s often a huge gap between a human language description of some procedure and realizing that procedure in software. I was reminded of that when I got the idea to apply my “IsEqual” and “Comparable” protocols to a class representing a line (vector). I remembered that calculating the length of a line is based on the Pythagorean Theorem (see here and here), and line length was key to comparing lines with the ==, !=, <, >, <=, and >= operators. My "Line" class would come in handy in, for example, a drawing app or game, where the user taps on two locations on screen to create a line between two points.

Custom class adopting multiple protocols
Here's my "Line" class, which adopts two protocols, "IsEqual" and "Comparable:"

Verifying your algorithms
I used a spreadsheet, Apple Numbers, and prepared a visual representation of two vectors to do some basic testing of my "Line" class's length() method:


Here's my test code for the points shown in the chart above:

Testing/prototyping UI with "Single View" Xcode playground template
Did you know that you can prototype and test your user interface (UI) using an Xcode 9 "Single View" playground template? It's pretty awesome -- a great time saver and tool for rapid prototyping. In order to more robustly test my "Line" class, I created just such a playground. Assignment: I want you to try this out yourself before I explain it. I will show you my playground's code, simulator output, and my Swift test statements.

Here's my playground code:

Here's the visual output of my view from the playground simulator:

Here's Swift code for testing my "Line" class instances matching the vectors I drew in the playground:

Wrapping up -- and why I write
I hope you all learned something about protocols -- and about all the other skills a good developer should always be striving to improve. I'd like to share my motivation for publishing this blog.

My goal is to help you become well-rounded software developers who engage in critical thinking, understanding why you want to use certain methodologies and tools. Becoming a good developer, computer scientist, software engineer -- whatever you want to call yourself -- means learning, practicing, and experiencing so much that you evolve into a mensch (yes, that term applies to females as well as males). You need to realize that being a developer means you become much more than a technician who's memorized say, the Swift language, and only knows how to build an application using say, Xcode. What if your employer throws you into Android/Eclipse or C# .NET/Visual Studio development? You need to profoundly and instinctively understand algorithms, troubleshooting, design patterns, testing regimens, frameworks, architectures, compilation, linking... I hope you look up the definitions for these terms -- and hope you see where I'm going with this.



Author: Andrew Jaffee

Avid and well-published author, software engineer, designer, and developer, now specializing in iOS mobile app development in Objective-C and Swift, but with a strong background in C#, C++, .NET, JavaScript, HTML, CSS, jQuery, SQL Server, MySQL, Oracle, Agile, Test Driven Development, Git, Continuous Integration, Responsive Web Design, blah, blah, blah ... Did I miss any fad-based catch phrases? My brain avatar was kindly provided by https://icons8.com under a Creative Commons Attribution-NoDerivs 3.0 Unported license.

Leave a Reply

Your email address will not be published. Required fields are marked *