Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly referencing self in dispatch_async

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!

like image 873
LB. Avatar asked Jun 22 '14 01:06

LB.


1 Answers

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!

like image 195
Jack Avatar answered Nov 06 '22 11:11

Jack