/

Swift Protocols: Enhancing Object Functionality

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
2
3
protocol Mammal {

}

Structs and classes can adopt a protocol by indicating it after the colon:

1
2
3
4
5
6
7
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:

1
2
3
4
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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:

1
2
3
4
5
6
7
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.