I have a basic question. I'm working on a project with many delegate patterns, and would like reference on the best way about initializing them..
Here's some ideas with a test delegate I made:
Option 1:
It fails because I'm initilizing the delegate to self before super.init()
protocol MyClassDelegate {
func doSomething()
}
class MyClass {
var delegate: MyClassDelegate!
init(delegate: MyClassDelegate){
self.delegate = delegate
}
func myClassFuction(){
self.delegate.doSomething()
}
}
class ClassConformingToDelegate: NSObject, MyClassDelegate {
let myClass: MyClass
override init(){
myClass = MyClass(delegate: self) // Error because it's called before super.init
super.init()
}
func doSomething(){
//called from the delegate
}
}
Option 2:
It works, but then I risk having the delegate be nil.. Would I have to run a 'if delegate != nil' check each time I want to call a method? Is there a way around that? Is it a good practice to init the delegate this way?
protocol MyClassDelegate {
func doSomething()
}
class MyClass {
var delegate: MyClassDelegate!
init(){
}
func myClassFuction(){
self.delegate.doSomething() // might fail if delegate is nil
}
}
class ClassConformingToDelegate: NSObject, MyClassDelegate {
let myClass: MyClass
override init(){
myClass = MyClass()
super.init()
myClass.delegate = self // works because called after super.init
}
func doSomething(){
//called from the delegate
}
}
Those were just a couple ideas. I'm just trying to learn the best way of doing it. I'm open to all suggestions.
Thanks!!