a piece of source code that can pass around just like any other type of object.
The difference between a closure and regular source code is that
the code from the closure does not get perform right away.
It is stored in a "closure object" and can be performed at a later point, even more than once.
Just like a method or function, a closure can accept parameters.
They are separated from the source code by the "in" keyword.
Thanks to Swift's type inference you don't need to specify the data types of the parameters.
However, you could write them out in full if you want to.
If a closure is the last parameter of a method, you can use trailing syntax to simplify the code a little.
Closures are useful for other things too, such as initializing objects and lazy loading.
It is no coincidence that closures look a lot like functions.
In Swift closures, methods and functions are really all the same thing.
For example, you can supply the name of a method or function when a closure is expected, as long as the parameters match.
That somewhat negates one of the prime benefits of closures - keeping all the code in the same place - but there are situations where this is quite useful (the method acts as a "mini" delegate.)
Closures capture any variables use inside it, including self.
This can create ownership cycles, often leading to memory leaks.
To avoid this, you can supply a capture list.
Swift also has the concept of "no escape" closures.
Closure
A closure is simply
It is stored in a "
closure object
" and can be performed at a later point, even more than once.Just like a method or function, a closure can accept parameters.
Thanks to Swift's
type inference
you don't need to specify the data types of the parameters. However, you could write them out in full if you want to.If a closure is the last parameter of a method, you can use
trailing syntax
to simplify the code a little.Closures are useful for other things too, such as initializing objects and lazy loading.
It is no coincidence that closures look a lot like functions.
This can create ownership cycles, often leading to memory leaks. To avoid this, you can supply a capture list.
Swift also has the concept of "no escape" closures.