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:
Continue reading “Understanding Swift 4 protocols and using them in your apps”