title: When to init a delegate in Swift
body: <p>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.. </p>
  
  <p>Here's some ideas with a test delegate I made:</p>
  
  <h2>Option 1:</h2>
  
  <p>It fails because I'm initilizing the delegate to self before super.init()</p>
  
  <pre><code>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
      }
  }
  </code></pre>
  
  <h2>Option 2:</h2>
  
  <p>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?</p>
  
  <pre><code>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
      }
  }
  </code></pre>
  
  <p>Those were just a couple ideas. I'm just trying to learn the best way of doing it. I'm open to all suggestions. </p>
  
  <p>Thanks!!</p>