In this tutorial, we will be delving into the usage of protocols in Swift. Protocols are an essential part of Swift that allow you to define a blueprint of methods, properties, and other requirements.
By the end of the tutorial, you will understand:
- What protocols are.
- How to define and implement protocols.
- How to use protocol-oriented programming.
Prerequisites:
- Basic knowledge of Swift syntax and data types.
Protocols are a way of describing what properties and methods something must have. You then tell Swift which types use that protocol – a process known as adopting or conforming to a protocol.
You can define a protocol with the protocol
keyword, followed by the protocol's name (always start the name with a capital letter).
protocol SomeProtocol {
// protocol definition goes here
}
Once you've defined a protocol, you can implement it in your classes, structures, or enumerations.
struct SomeStructure: SomeProtocol {
// structure definition goes here
}
Let's define a Person
protocol that requires a name
property and a greet()
method:
protocol Person {
var name: String { get } // read-only property
func greet() // method
}
Now, let's create a Student
struct that adopts the Person
protocol:
struct Student: Person {
var name: String
func greet() {
print("Hello, my name is \(name).")
}
}
We can create a Student
instance and call its greet
method:
let student = Student(name: "John")
student.greet() // "Hello, my name is John."
Protocols can require methods to be mutating
. This means they can modify (or mutate) the instance it belongs to:
protocol Togglable {
mutating func toggle()
}
enum OnOffSwitch: Togglable {
case off, on
mutating func toggle() {
switch self {
case .off:
self = .on
case .on:
self = .off
}
}
}
var lightSwitch = OnOffSwitch.off
lightSwitch.toggle() // .on
In this tutorial, we have learned about protocols in Swift. We've seen how to define protocols, how to implement them in our own types, and how to use protocol-oriented programming. Protocols are a powerful feature in Swift and are at the heart of many Swift design patterns.
Next steps:
- Learn about protocol inheritance.
- Learn about protocols with default implementations.
Vehicle
protocol with a speed
property and an accelerate()
method. Implement it in a Car
struct.Printable
protocol with a printDetails()
method. Implement it in a Book
struct and a Person
struct.Solutions:
protocol Vehicle {
var speed: Int { get }
mutating func accelerate()
}
struct Car: Vehicle {
var speed: Int = 0
mutating func accelerate() {
speed += 10
}
}
protocol Printable {
func printDetails()
}
struct Book: Printable {
var title: String
func printDetails() {
print("Book title: \(title)")
}
}
struct Person: Printable {
var name: String
func printDetails() {
print("Person's name: \(name)")
}
}
Feel free to play around the code and try different things to get a better understanding. Happy learning!