I’d like to be able to require that a delegate be set on an object, but the object that is initializing this is supposed to be the delegate. You can see the example below.
The only reasonable way I’ve found to handle this is that I need to create a setup(withDelegate:) method, but this doesn’t make it a compile time requirement that you set the delegate property. There are other suggestions I’ve had, but none have given the compile time safety I want.
Does anyone have any other ideas that satisfy these requirements? It seems to me like it would have to be a change to the language.
Note: I know a delegate should usually be optional. In my case it’s not actually a delegate but a protocol for something, but this is to illustrate my point more easily.
protocol BDelegate: class {
func foo()
}
class B {
weak var delegate: BDelegate?
init(delegate: BDelegate) {
self.delegate = delegate
}
}
class A: UIViewController, BDelegate {
let b: B
init() {
b = B(delegate: self) // ERROR: using self before all properties initialized
super.init(nibName: nil, bundle: nil)
}
func foo() {}
}
Yes. That works however, then you have a var that could changed throughout the class which isn’t great and an IUO, which also isn’t great. I agree that does work.