10.1. Adopting a protocol
A protocol contains only the declarations of the properties and functions that are needed to be adopted and implemented by a struct or class. For example, let's define our own USB interface, USBMad.
We can define our own USBMad protocol with a few guidelines:
We need an id of the device to implement this protocol.
We have the option to support a display adapter through that port.
We have the option to support audio through that interface.
We must implement charging through the port.
We must implement data transfer through the port.
So we define the protocol where we declare three variables, id - for the device ID, supportsDisplayAdapter - to decide whether we would implement the display feature, and supportsAudio - to decide whether we would implement the audio or not. We also declare two methods to say this USBMad protocol must provide functionalities to charge the accessories and transfer data.
protocol USBMad{
var id:Int{get}
var supportsDisplayAdapter:Bool{get}
var supportsAudio:Bool{get}
func chargeAccessories()
func transferData()
}You might be confused about {get} declarations you see in the code. It means the property is a gettable property when implemented. You can also declare a property both gettable and settable by declaring {get set}. I will not dig deeper into these declarations; for now, I will just use {get}. For more information, you can read this article.
Now, let's adopt our USBMad protocol in our MyLaptop struct:
struct MyLaptop: USBMad{
//struct's own properties
var name:String
var architecture:String
//adopted/conformed variables and methods
var id: Int
var supportsDisplayAdapter: Bool
var supportsAudio: Bool
//adopted and to be implemented methods
func chargeAccessories() {
//MyLaptop's implementation of adopted method
print("I am able to charge the accessories!")
}
func transferData() {
//MyLaptop's implementation of adopted method
print("You can send/receive data to/from me!")
}
}Here, we are defining our struct MyLaptop where we adopt the USBMad protocol. We wrote MyLaptop : USBMad to say that MyLaptop adopts USBMad protocol. MyLaptop has it's own variables, name and architecture. Also, since it adopts the USBMad protocol, it must adopt the properties and methods of USBMad and implement them.
So we can create an instance of MyLaptop like the following:
See, we not only have to initialize MyLaptop's own properties but must also initialize the properties MyLaptop adopts from USBMad.
Let's add another method describe() to MyLaptop:
Calling myLaptop.describe() prints:
These are the CliffsNotes version of adopting/confirming a protocol. You will see extensive use of protocols in iOS development.
Reference code
Last updated
Was this helpful?