Swift Protocols Made Easy Tutorial
Protocol based programming is a difficult concept to initially understand in Swift. In this tutorial we cover this in an intuitive way so you too can take full advantage of protocol based programming.
Your first protocol
Create a new single view application in XCode. Then add a new blank Swift file with File–>New–>Swift File. Name the file PetProtocol.swift and code it as follows.
import UIKit protocol Pet { var name: String {get} var age: Int {get set} var legs: Int {get set} func makeSound() }
This creates our first protocol which is a Pet. This Pet protocol can be applied to any Class, Enumeration or Structure. Essentially this is a set of “rules”. Our Pet protocol enforces the following to anything it is applies to:
- Must have a name variable that you can retrieve
- Must have an age variable that you can retrieve or set
- Must have a legs variable that you can retrieve or set
- Must have a function called makeSound
The idea behind this is that our Pet protocol can be applied to anything that we want to take on the characteristics of a Pet, this enforces these rules.
Go back to our default view controller and add the Pet protocol to it as follows:
class ViewController: UIViewController, Pet {
You will notice an error now comes up – the class doesn’t confirm to protocols? Relax – that is fine, as we now need to add the items in the protocol to confirm to it’s rules.
Add the class level variables as follows, lets create a Pet called Fido that is 20 years old with 4 legs as follows:
let name: String = "Fido" var age: Int = 20 var legs: Int = 4
Then add in the makeSound function. Fido is a dog so he goes “Woof”
func makeSound() { print("Woof") }
Next in viewDidLoad add the following to output some information about our cuddly Fido.
override func viewDidLoad() { super.viewDidLoad() age += 1 print("\(name) is \(age) years old and has \(legs) legs") makeSound() }
See how the error is gone now! You can run the app and see it output information about Fido.
So as you can see by applying this “Pet” protocol to our View Controller class it now must abide by the protocol rules, so we have to add in the variables and functions that are in the Pet protocol to our class.
Protocol oriented programming?
The idea of this is protocol oriented programming. We can split functional components into something reusable (A protocol). You can apply several protocols to a Class, Enumeration or Structure. You can also create default behavior for protocol values or functions so you don’t need to explicitly set it everywhere you use it.
Create a new Swift file called ClothingProtocol.swift and create the protocol as follows:
import UIKit protocol Clothing { var sunglasses: String {get set} var type: String {get set} }
Now lets say we want our sunglasses to be Raybans by default, and if is anything else then we will set it to the object that conforms to the protocol. To do this add the following extension to our Clothing Protocol, it will set sunglasses to be Raybans by default.
extension Clothing { var sunglasses: String {return "Raybans"} }
Now lets add the Clothing protocol to our ViewController that also contains our pet
class ViewController: UIViewController, Pet, Clothing {
You will notice we get another the “class doesn’t confirm to protocols error”. To fix this add the type (This is from the clothing protocol) to it.
var type: String = "Casual"
Next in viewDidLoad add the following print statements
print(type) print(sunglasses)
You will see the following output:
Fido is 21 years old and has 4 legs Casual Raybans
So looking at the output related to our clothing protocol we can tell:
- We set the type to “Casual”
- We did not set the sunglasses value, this is set to “Raybans” by default with the extension for Clothing
So if we wanted to set a separate sunglasses value and not use the default “Raybans” valuer simply add it as a class level variable, like we had to for the other protocol objects. This “Overrides” it so to speak.
var sunglasses: String = "Oakley"
Run the program and you will see it print out Oakley to the console!
Why use protocol oriented programming?
A protocol is like a construction supervisor having a set of blueprints to build a house. The supervisor does not know how to build the house, but can instruct other people with special skills (Bricklayer, Electrician, Plumber) to do so. The idea behind POP (Protocol oriented programming). The idea behind it is you can mix and match protocols for objects and methods you only need, where as with object oriented programming (OOP) your sub classes will inherit everything from it’s parent.
So next time your making an app ask yourself if protocol oriented programming might be more suitable to the problem your facing.