I have been reading the swift programming guide in iBooks. Could someone explain to me what is the difference between a function and a closure. Is it just that it has no name and can be used in expressions?
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
But as explained above, in JavaScript, all functions are naturally closures (there is only one exception, to be covered in The "new Function" syntax). That is: they automatically remember where they were created using a hidden [[Environment]] property, and then their code can access outer variables.
Function objects (C++) As of the 2011 revision, the C++ language also supports closures, which are a type of function object constructed automatically from a special language construct called lambda-expression.
Although C was created two decades after Lisp, it nonetheless lacks support for closures.
First, let's start with definition of Closure, as found in Wikipedia:
In programming languages, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables or upvalues) of that function.
Closure is the term that is used to refer to a function along with the variables from its environment that it "closes".
The definition of Closure in Swift is inline with lambdas and blocks in other languages like C# and Ruby.
As for the difference from functions, from the Swift documentation:
Global and nested functions, as introduced in Functions, are actually special cases of closures
So all functions are essentially closures that store references to variables in their context.
Closure expressions
are convenient way of writing closures, and provides more terse syntax.
Functions are, in fact, just named closures. The following are at least conceptually equivalent:
let foo = { println("hello") }
func foo()->(){ println("hello") }
This gets a little more complicated in the case of using func
to declare methods, as there's some interesting bits of sugar added regarding the automatic insertion of public named parameters, etc. func myMethod(foo:Int, bar:Int, baz:Int)
becomes func myMethod(foo:Int, #bar:Int, #baz:Int)
, for example.
But it's still true that even methods are just a specific case of closures, and if it's true of closures, it's true of functions and methods as well.
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