title: Swift Delegate and Optional
body: <p>I'm working on my first iOS app using swift. I'm trying to load the a value from one viewController into another. I am using a protocol, but I can't get it to execute properly. I have searched around both stack overflow and elsewhere but haven't been able to find an answer that works in my situation. </p>
  
  <p>Here's the VC I'm trying to pull the value from:</p>
  
  <pre><code>protocol AddHelperVCDelegate {
      func didFinishAddingHelper(controller: AddHelperViewController)
  }
  
  class AddHelperViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {
  
      @IBOutlet weak var tableView: UITableView!
  
      let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext!
      var fetchedResultsController:NSFetchedResultsController = NSFetchedResultsController()
  
      var delegate:AddHelperVCDelegate! = nil
      var helperBonus:NSNumber = 0
      override func viewDidLoad() {
          super.viewDidLoad()
  
          fetchedResultsController = getFetchResultsController()
          fetchedResultsController.delegate = self
          fetchedResultsController.performFetch(nil)
  
          // Do any additional setup after loading the view.
      }
  }
  </code></pre>
  
  <p>And here is where I am trying to move the value (and the view) back to a proceeding VC.</p>
  
  <pre><code>// UITableViewDelegate
  
  func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
  
      var indexPathForRow = tableView.indexPathForSelectedRow()
      println("indexPath for selected row is: \(indexPathForRow)")
  
      let thisUser = fetchedResultsController.objectAtIndexPath(indexPath) as UserModel
      var cell:UserCell = tableView.dequeueReusableCellWithIdentifier("helperCell") as UserCell
  
      helperBonus = thisUser.effectiveCombat
      helperBonus = Int(helperBonus)
  
      println("helperBonus is: \(helperBonus)")
  
      delegate.didFinishAddingHelper(self)
  
  }
  </code></pre>
  
  <p>If I make the delegate an optional (<code>delegate?.didFinishAddingHelper(self)</code>) then nothing happens. If I do not, I get a crash with the error message:</p>
  
  <pre><code>indexPath for selected row is: Optional(&lt;NSIndexPath: 0xc000000000018016&gt; {length = 2, path = 0 - 3})
  helperBonus is: 0
  fatal error: unexpectedly found nil while unwrapping an Optional value
  </code></pre>
  
  <p>Now, I know I'm declaring delegate as nil, but that's the limit to my understanding of what's going on. I need to add the value in the proceeding VC in this function:</p>
  
  <pre><code>func didFinishAddingHelper(controller: AddHelperViewController) {
      self.effectiveCombat = Int(controller.helperBonus)
      controller.navigationController?.popViewControllerAnimated(true)
  }
  </code></pre>