Brendon Cheung
Brendon Cheung

Reputation: 1035

How does a delegate knows where to invoke function where there are multiple conformance

I am just beginning to understand the delegation pattern in iOS swift. Correct me if I am wrong but here is my understanding:

The delegation pattern is used to delegate tasks to another class in order to keep class having one job and one job only, any jobs that are irrelevant will be delegated to another class that is responsible this job. Now here is the confusing part:

protocol Addition {
    func addTwoNumbers(_ number1: Int, _ number2: Int)
}

class A: Addition {

    func addTwoNumbers(_ number1: Int, _ number2: Int) {
        print("The number is: \(number1 + number2)")
    }
}

class B {

    let apple = 10
    let orange = 20

    var delegate: Addition?

    func runAddition() {
        delegate?.addTwoNumbers(apple, orange)
    }
}

let bob = B()
bob.runAddition()

class B need to perform an addition task and instead of implementing the function, I'll let class A to do the job through a protocol. Now here is what where I am confused. How does class B know where to run the func addTwoNumbers function? I mean I can having another class called class C and conform to the Addition protocol, now I have two classes conforming to the Addition protocol, how would class B know where to go?

thanks!

Upvotes: 0

Views: 36

Answers (1)

Mo Abdul-Hameed
Mo Abdul-Hameed

Reputation: 6110

When you call runAddition() method of class B it will do nothing, because there is no value set for delegate.

To make it work, you need to assign an instance of any class that implements Addition protocol.

Let's say for example we have 2 classes that implement Addition protocol:

class Calculator1: Addition {

    func addTwoNumbers(_ number1: Int, _ number2: Int) {
        print("Inside Calculator1 addTwoNumbers method")
        // The rest of your code
    }
}

And

class Calculator2: Addition {

    func addTwoNumbers(_ number1: Int, _ number2: Int) {
        print("Inside Calculator2 addTwoNumbers method")
        // The rest of your code
    }
}

Now, let's create 2 objects of the previous classes:

let calculator1 = Calculator1()
let calculator2 = Calculator2()

Let's create an instance of class B:

let bob = B()

Now, let's set the delegate of bob and call runAddition() method:

bob.delegate = calculator1
bob.runAddition()

The output of runAddition() here will be:

Inside Calculator1 addTwoNumbers method

Now, let's set another value for the delegate, and call runAddition() again:

bob.delegate = calculator2
bob.runAddition()

The output of runAddition() here will be:

Inside Calculator2 addTwoNumbers method

Hope this helps!

Upvotes: 1

Related Questions