Swift Protocols: Enhancing Object Functionality
tags: [“Swift”, “Protocols”, “Object Functionality”]
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:
1 | protocol Mammal { |
Structs and classes can adopt a protocol by indicating it after the colon:
1 | struct Dog: 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:
1 | protocol Mammal { |
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:
1 | struct Dog: Mammal { |
Additionally, structs and classes can adopt multiple protocols by listing them after the colon:
1 | struct Dog: 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.