Swift 3: Protocol Part 2
So moving onward from part 1 to explore more about the Protocol. Let's start it!! below mentioned example checked on Xcode 8.1
Protocol Property Requirements -
Property requirement always needs to declare as var. Property can be declared as gettable and settable, {get} and {get set} respectively.
protocol myProtocol {
var canBeSetAndGet: Int { get set }
var canBeGet: Int { get }
}
Type property can be prefixed with a class or static keyword when you declare in Protocol.
protocol myProtocol {
static var myProperty:String {get set}
}
protocol myProtocol {
var myProperty:String {get set}
}
protocol myProtocol {
static func someMethod()
}
Type method requirements for the protocol are the same way as type property for the protocol. We need to add the same static or class keyword prefix for the type method when implemented by the type.
@objc protocol SomeProtocol {
@objc optional static func test()
}
The @Objc keyword is for Objective - c interoperability and it indicates that your class or protocol should be accessible to Objective - C code.
Sometimes we need to modify the instance which belongs to the function then we put the mutating keyword before the function to mutate the instance and instance properties.
As Apple said: If you mark a protocol instance method requirement as mutating, you do not need to write the mutating keyword when writing an implementation of that method for a class. The mutating keyword is only used by structures and enumerations.
protocol Togglable {
mutating func toggle()
}
enum StartStopWatch: Togglable {
case stop, start
mutating func toggle() {
switch self {
case .stop:
self = .start // mutating instance
case .start:
self = .stop // mutating instance
}
}
}
var lightSwitch = StartStopWatch.start
lightSwitch.toggle() // off
Protocol Initializers -
The class which is marked with the final can not use the required because final classes cannot be subclassed.
Note: If the subclass overrides the designated initializer from its superclass and the same method from protocol the mark that initializer method with required override.
protocol myProtocol {
init()
}
class mySuperClass {
init() {}
}
class mySubClass: mySuperClass, myProtocol {
required override init() { }
}
Failable Initializers Requirements :
Protocol conformance with Extension :
class mySuperClass {
init() {}
}
protocol TexToRepresent {
var textRepresntataion: String { get }
}
extension mySuperClass: TexToRepresent {
var textRepresntataion: String {
return "text representation"
}
}
var myobj = mySuperClass()
myobj.textRepresntataion //"text representation"
Comments
Post a Comment