Protocol Oriented Programming in Swift
"A protocol defines a blueprint of methods, properties… The protocol can then be adopted by a class, structure, or enumeration." - Apple
- An advantage of protocols in Swift is that objects can conform to multiple protocols.
- POP encourages flat and non-nested code.
- Swift supports only multiple inheritance of protocols.
- Value Type:- (Although value types do not support inheritance in Swift, they can conform to protocols.)
Defining struct:
We can create struct
as person
Defining protocol:
- I have created
protocol
as Details, to get info about person - Inside the
protocol
block, when we describe a property, we must specify whether the property is only gettable{ get }
or both gettable and settable{ get set }
When we fail to mention { get }
or { get set }
to a property, it show error like
Extension for struct:
extension Person: Details {
var fullName : String {
get {
return firstName + " " + (lastName ?? "")
}
}
func sayHi() {
print("Hi, My self \(fullName), I have \(experience) years of experience in iOS Development.")
}
}
Just call like
Output:
Protocol Composition:
"Multiple protocols at the same time"
struct Person: Details, Experience, Domain {
var fullName: String
var experience: Int
var domain: String
func sayHi() {
print("Hi, My self \(fullName), I have \(experience) years of experience in \(domain).")
}
}
Just call like
Output:
Optional Protocol:
Here domain will be optional
, we may include or we may not.
Protocol Extension:
We can create extension
for protocol
You can just call like
Protocol as Type (Last):
We can create struct
as StructDetails
We can create class
as ClassDetails
Now, let’s make object for struct
& class
Now, you can add them into an array.
let arraySayHi: [SayHi] = [structDetails, classDetails]
for sayhi in arraySayHi {
print(sayhi.sayHi())
}
Output:
protocol
is wonderful, try it in your code & enjoy.
Reference:
Let's grow together 🌱
Cheers 🍻