I am trying to get my head around delegation and am stripping it down to a basic implementation. I've came up with this, but the delegate function never gets called. Could anyone shed some light?
protocol MyDelegate{
func delegatedFunction (a:String)
}
class DelegatorClass {
var delegate: MyDelegate?
func callDelegate() {
delegate?.delegatedFunction("hello")
}
}
class DelegateClass: MyDelegate {
func delegatedFunction (a:String){
print(a)
}
}
You don't have to use protocols...but you should if you want to keep things flexible. Delegation is in essence asking someone else to do something for you. If you enforce a contract, then its more likely they will do it for you.
Protocol: A set of methods that would be implemented by the class which conforms to that protocol. Delegate: The reference to that class which conforms to the protocol and will adhere to implement methods defined in the protocol.
let myDelegatorObj = DelegatorClass()
myDelegatorObj.delegate = DelegateClass()
myDelegatorObj.callDelegate()
Point is before you call callDelegate()
you need to assign the delegate
. To check your delegation working, you can initialize the DelegatorClass
with the delegate.
class DelegatorClass {
var delegate: MyDelegate? = DelegateClass()
func callDelegate() {
delegate?.delegatedFunction("hello")
}
}
protocol MyDelegate{
func delegatedFunction (a:String)
}
class DelegatorClass {
var delegate: MyDelegate?
func callDelegate() {
delegate?.delegatedFunction("hello")
}
}
class DelegateClass: MyDelegate {
func delegatedFunction (a:String){
print(a)
}
}
let delegator = DelegatorClass()
delegator.callDelegate() // print nothing, because delegate is nil by default
// set your delegate !!!!!!!
delegator.delegate = DelegateClass()
delegator.callDelegate() // print "hello"
It is nothing wrong with your approach, just use it the right way. The point is set delegate variable to some instance of type T conforming to protocol MyDelegate. In your case this is DelegateClass instance. Generally, T could be almost everything conforming to MyDelegate protocol.
struct S:MyDelegate {
func delegatedFunction(a: String) {
print("Hello from struct conforming to MyDelegate protocol")
}
}
delegator.delegate = S()
delegator.callDelegate() // print "Hello from struct conforming to MyDelegate protocol"
delegator.delegate = nil
delegator.callDelegate() // print nothing again :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With