00. Three forms of Closures

It will take about 1 minutes to finish reading this article.

As the Apple official documents says, closures take one of three forms:

1. Global functions

Global functions are closures that have a name and don’t capture any values.

1
2
3
func setupBlock {
print("Hello")
}

It is a special closure.

2. Nested functions

Nested functions are closures that have a name and can capture values from their enclosing function.

1
2
3
4
5
6
7
8
9
func makeIncrementer() -> () -> Int {
var runningTotal = 10
// nested function,it is a closure too.
func incrementer() -> Int{
runningTotal += 1
return runningTotal
}
return incrementer
}

3. Closure expressions

Closure expressions are unnamed closures written in a lightweight syntax that can capture values from their surrounding context.

1
2
3
{ (param) -> ReturnType in
// Method body
}

Swift’s closure expressions have a clean, clear style, with optimizations that encourage brief, clutter-free syntax in common scenarios. These optimizations include:

  1. Inferring parameter and return value types from context
  2. Implicit returns from single-expression closures
  3. Shorthand argument names
  4. Trailing closure syntax

Reference

https://docs.swift.org/swift-book/LanguageGuide/Closures.html