A protocol defines a blueprint of methods, properties and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure or enumeration to provide an actual implementation of those requirements.
Protocol Syntex:
We can define protocols in a very similar way to classes, structure and enumerations.
protocol SomeProtocol {
// Protocol definition goes here
}
If we have multiple protocol then want to writen in struct or classes:
import Foundation
struct SomeClassOrStruct: ProtocolOne, ProtocolTwo, ProtocolThree {
//structure definition goes here
}
first written struct or class name then colon and finally protocol name separated by comma.
What should be done if we have superclasses?
Then we should import class before protocol that means after define subclass then colon and superclass:
import Foundation
struct ChildClass: AnotherSuperClass, ProtocolOne, ProtocolTwo, ProtocolThree {
//class definition goes here
}
Property Requirements:
Here's an example of a protocol with a single instance property requirement:
import Foundation
protocol UserName {
var fullName: String {get}
}
Here's an example of a structure that adopts and conforms to the UserName protocol:
struct Person: UserName {
var fullName: String
}
let userName = Person(fullName: \"joynal Abedin\")
print(userName.fullName) // output: joynal Abedin
Here's more complex class which also adopts and conforms to the UserName protocol:
class Person: UserName {
var fullName: String
init(fullName: String) {
self.fullName = fullName
}
}
let userName = Person(fullName: \"joynal Abedin\")
print(userName.fullName) // output: joynal Abedin
0 Comments
Leave a Comment