How do I properly reference self in a swift closure?
dispatch_async(dispatch_get_main_queue()) {
self.popViewControllerAnimated(true)
}
I get the error:
Cannot convert the expression's type 'Void' to type 'UIViewController!"
Randomly I tried:
dispatch_async(dispatch_get_main_queue()) { ()
self.popViewControllerAnimated(true)
}
and it worked. Not sure what the extra () does! Anyone care to explain? Thanks!
This is the same issue as people have run in with these questions:
What am I doing wrong in Swift for calling this Objective-C block/API call?
animateWithDuration:animations:completion: in Swift
Here is the general idea:
From the Swift book: https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Closures.html
One of the optimizations of Closures is:
Implicit returns from single-expression closures
Thus, if you just have one line in your closure, your closure's return value changes. In this case, popViewController
returns the view controller being popped. By adding ()
to the closure, you just made it a 2-line closure and the return value isn't implicit anymore!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With