简体   繁体   中英

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM