Search code examples
swiftblock

Single unwrap inside block in Swift


This gives me an error:

NSNotificationCenter.defaultCenter().addObserverForName(MyNotification, object: nil, queue: nil) { (notification: NSNotification?) in
    self.variable?.myMethod()
}

But this is fine:

NSNotificationCenter.defaultCenter().addObserverForName(MyNotification, object: nil, queue: nil) { (notification: NSNotification?) in
    println()
    self.variable?.myMethod()
}

Any idea why and how to solve it?

Thank you.


Solution

  • What you're seeing is "implicit returns". Swift assumes that if you have a single expression as the implementation of a closure, then it returns the result of that line of code from the closure. This is a optimization documented in Apple's Swift Programming Language text (check the last paragraph/bullet list in the Closures intro).

    Because of this, if you're required to have a return statement if you don't want to implicitly return from the first statement.

    So your code should look like:

    NSNotificationCenter.defaultCenter().addObserverForName(MyNotification, object: nil, queue: nil) { (notification: NSNotification?) in
      self.variable?.myMethod()
      return
    }