First, I'd like to point to:
1- Creating a singleton Class should contains:
private init() {}
That leads to enforce to access the class only by using its shared instance.
2- As mentioned in Max's Answer, the delegate should be optional and has a weak reference.
3- The protocol should be a type of class, as follows:
protocol AClassDelegate: class
For more information, you might want to check this Q&A.
Now, let's assume -for testing purposes- that the method1()
from AClassDelegate
should be get called when calling foo()
from A
class:
protocol AClassDelegate: class {
func method1()
}
class A {
private init() {}
static let shared = A()
weak var delegate: AClassDelegate?
func foo() {
print(#function)
delegate?.method1()
}
}
Let's implement classes that conforms to AClassDelegate
:
class B: AClassDelegate {
func bar() {
A.shared.delegate = self
A.shared.foo()
}
func method1() {
print("calling the delegate method B Class")
}
}
class C: AClassDelegate {
func bar() {
A.shared.delegate = self
A.shared.foo()
}
func method1() {
print("calling the delegate method C Class")
}
}
Output should be:
let b = B()
b.bar()
// this will print:
/*
foo()
calling the delegate method B Class
*/
let c = C()
c.bar()
// this will print:
/*
foo()
calling the delegate method C Class
*/