Swift Closures
Most modern languages have closures, or they may be called anonymous functions. In Swift we think of them as closures, and they are used heavily for callbacks throughout their use.
Prerequisites:
- Functions
- Types
Motivation
We can take Apple’s explanation step-by-step “…self-contained blocks of functionality that can be passed around and used in your code”. Closures are pretty fundamental building blocks in Swift, and need to be taken seriously.
Self-contained blocks of functionality
Meaning we can use closures to write code that perform a specific task.
can be passed around and used in your code
We can pass these closures around, store them, pass arguments to as function and treat them pretty much as you would any other object in Swift. It is very common to pass closures around as completion handlers in Swift, and use them for event handling and callbacks.
The basic closure(s)
Assign it to a variable
We take what we think would be a function, and assign it to a variable.