Reputation: 5234
Class A is the delegate. Class B had a protocol with the methods, and I could call them simply by calling something like delegate?.myFunc()
protocol ClassBDelegate: class {
func myFunc()
}
class Class B {
weak var delegate: ClassBDelegate?
delegate?.myFunc()
}
But now myFunc() is in a another class (Class C) that Class A uses, but now I want Class B to call a function in Class A's instance of Class C.
How is that done? I know there's an answer, but maybe I don't know what to search for? I wish I could write something like delegate?.classC.myFunc() but it won't let me do that.
Upvotes: 0
Views: 147
Reputation: 131418
The whole point of a protocol is that it decouples you from having to specify a particular class that provides a service. Instead, you just specify that some object that conforms to the protocol provides the service.
You just need to make both your ClassA and ClassB objects have the same delegate. Then each one will call the delegate directly.
Upvotes: 1
Reputation: 535201
It's not class B's business to know anything about what its delegate does in order to fulfill its commands. That is the point of the protocol / delegate pattern. The protocol hides the implementation — more than that, the very identity — of the delegate.
It is class A, serving as the delegate, that will respond to myFunc
by talking to its class C helper in some way. Maybe that is its delegate, I don't know. That doesn't matter. But don't change anything about class B's knowledge of the situation or the way it talks.
So, you need to write a function in class A that will call its class C for you. Class B should know nothing about what happens at the far end if class A is the delegate. That's a private implementation detail.
Upvotes: 2