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?
2 Answers
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.

- 290,304
- 63
- 469
- 417
-
@jemmons - I am still adding the answer. – manojlds Jun 08 '14 at 17:21
-
1@jemmons - true. I usually iterate over my answers, but clicked submit too quick in this case. – manojlds Jun 08 '14 at 17:29
-
Functions are a special kind of closures. One difference is function always start with "func" keyword. There are three kinds of closures: 1) Global functions – They have a name and cannot capture any values 2) Nested functions – They have a name and can capture values from their enclosing functions 3) Closure expressions – They don’t have a name and can capture values from their context – Dipak Jul 26 '21 at 05:51
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.

- 18,605
- 8
- 55
- 84
-
-
Almost. In javascript, closures are anonymous functions. In Swift, functions are named closures. But I'll freely admit that distinction is mostly semantic and not very important. – jemmons Nov 05 '14 at 20:22
-
1"In javascript, closures are anonymous functions. In Swift, functions are named closures." These two definitions are equivalent. It sounds like there is no difference, semantic or otherwise. – Will Aug 14 '17 at 00:12