4

I was asked whether Objective C blocks are more similar to closures or callbacks. However, the definition of a callback seems nearly identical to a closure, at least in this example borrowed from http://swiftspace.org/callback-function-in-swift/:

func mainFunction(callback: () -> Void) {

   // some code
   callback()   // call the callback function
}

In the Programming Language Guide (Swift 2.2) callbacks are rarely mentioned, with this one notable exception where a callback sounds like a type of closure:

“When a closure’s type is already known, such as the callback for a delegate, you can omit the type of its parameters, its return type, or both.”

Help?

TylerH
  • 20,799
  • 66
  • 75
  • 101
squarehippo10
  • 1,855
  • 1
  • 15
  • 45
  • 1
    Possibly answered (intuited from) here: http://stackoverflow.com/questions/2070275/javascript-closures-and-callbacks – TylerH Apr 08 '16 at 13:09

1 Answers1

5

They are two completely different, although compatible, concepts. A callback is a hook for a function to be attached to so that when an action is needed the function can be called to provide a result or affect. A closure is a function that captures local variables to be used in a scope outside of the local scope. A closure can be a callback just like any other function can be a callback but it's not limited to that use.

In your quote they are talking about how you can use a closure for the callback. In that case the compiler can infer the function signature (types of parameters and return) from the context.

Note that this has very little to do with Objective-C blocks. Swift and Objective-C are two completely different languages and blocks and closures are two different implementations of similar concepts.

  • I guess I'm having a hard time seeing them as two completely different concepts when they look so similar. So basically, the differences are:
    A callback is a hook for a function. A closure is a function. (Actually, I read that a function is a special type of closure, not to confuse the issue more.)
    A closure can capture local variables.
    A closure can be a callback but it can do other things as well...
    – squarehippo10 Apr 08 '16 at 18:48
  • In Swift a function is any piece of code that is callable, possibly with parameters and possibly with a return type. There are pre-defined free functions that exist within a scope and that have a function signature that includes a function name. There are also closure functions that are nameless and which take their parameters and return type from their calling context. As to which comes from which, well that's an implementation detail and really is no matter to most circumstances. –  Apr 08 '16 at 18:54