Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a basic implementation of Delegation in Swift?

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)
    }
}
like image 576
Paul Herron Avatar asked Feb 13 '16 23:02

Paul Herron


People also ask

Can delegation be implemented without a protocol Swift?

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.

What is delegate protocol in Swift?

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.


2 Answers

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")
    }
}
like image 91
Warif Akhand Rishi Avatar answered Oct 15 '22 13:10

Warif Akhand Rishi


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 :-)
like image 41
user3441734 Avatar answered Oct 15 '22 12:10

user3441734