Protocols — Swift 4
Q. What is a Protocol ?
A. “A protocol defines a blueprint of methods , properties and other requirements that suits a particular task or a piece of functionality” ~ Apple
A protocol can then be adopted by classes, structure , and enumeration to provide the actual implementation of those requirements.
Declaration of a protocol
protocol nameYourProtocol {
// You can define the properties , function inside these protocols
}
For Example,
protocol Person {
var firstName: String {get set}
var lastName: String {get set}
func getUpdates() -> String
}
An important thing to Note here is that while declaring a protocol we cannot use the type inference inside it . Like “var firstName: String “ this will give you an error , so to avoid the error you have to use get and set which stands for read-write and read-only respectively.
Conforming a protocol to a class, structure , or enumeration is done in the following way:
struct Student: Person {
internal var firstName: String
internal var lastName: String
}
Optional Requirements:
When we need to implement any method or property as an optional inside a protocol which may be or may not be implemented.
Use “@objc” attribute before the protocol .
Note: — Only classes can adopt the protocol with @objc attribute , while structure and enumeration cannot adopt it.
Example :
@objc protocol Phone {
var phoneNumber: String {get set}
@objc optional var emailID:String {get set} // declaring an optional property
@objc optional func getEmailID() //declaring an optional method
}
Protocol Inheritance
Inheritance is an useful and powerful feature that now protocol also uses. With the help of inheritance we can now inherit requirements from one or more additional protocols and then uses that requirement.
Example:
protocol thirdProtocol : firstProtocol , secondProtocol {
// add property and methods here
}
protocol person :thirdProtocol {
// it will hold it’s own as well as the thirdprotocol definition
}
What just happened here, that what’s you might be wondering? As you can see that the thirdProtocol is inheriting the firstProtocol and secondProtocol, so now instead of inheriting each protocol separately I just need to inherit the thirdProtocol as it has the methods and property from the inherited protocols.