Protocol in Swift allows different objects of different types to have a common set of functionality. It serves as a blueprint that defines a set of properties and methods that can be adopted by structs and classes.
To define a protocol in Swift, use the following syntax:
protocol Mammal {
}
Structs and classes can adopt a protocol by indicating it after the colon:
struct Dog: Mammal {
}
class Cat: Mammal {
}
A protocol can define properties and methods but does not provide values or implementations. They act as requirements that must be implemented by the adopting struct or class. For example:
protocol Mammal {
var age: Int { get set }
func walk()
}
In this example, the Mammal
protocol defines a property age
and a method walk()
. The property can be defined as get
or get set
. If it’s defined as get
, the property becomes read-only with a getter.
To conform to a protocol, a struct or class must implement the required methods and properties. Here’s an example:
struct Dog: Mammal {
var age: Int = 0
func walk() {
print("The dog is walking")
}
}
class Cat: Mammal {
var age: Int = 0
func walk() {
print("The cat is walking")
}
}
Additionally, structs and classes can adopt multiple protocols by listing them after the colon:
struct Dog: Mammal, Animal {
}
class Cat: Mammal, Animal {
}
It’s important to note that when adopting multiple protocols, if there is a superclass, it should be listed as the first item in the list, after the colon.