| Start |
|---|
| Closure basics Closures (opens new window) (also known as blocks or lambdas) are pieces of code which can be stored and passed around within your program. Like other functions, closures can accept arguments and return results or throw errors (opens new window): Closures can capture values from their scope: Closures can be passed directly into functions: |
| Syntax variations The basic closure syntax is
Many of these parts can be omitted, so there are several equivalent ways to write simple closures:
|
| Passing closures into functions Functions may accept closures (or other functions) as parameters: Trailing closure syntaxIf a function's last parameter is a closure, the closure braces If a function's only argument is a closure, you may also omit the pair of parentheses |
Captures, strong/weak references, and retain cycles When a closure captures a reference type (a class instance), it holds a strong reference by default: The closure's capture list can be used to specify a weak or unowned reference: For more information, see the Memory Management (opens new window) topic, and the Automatic Reference Counting (opens new window) section of The Swift Programming Language. Retain cyclesIf an object holds onto a closure, which also holds a strong reference to the object, this is a retain cycle (opens new window). Unless the cycle is broken, the memory storing the object and closure will be leaked (never reclaimed). |
| Using closures for asynchronous coding Closures are often used for asynchronous tasks, for example when fetching data from a website. This function is asynchronous, so will not block the thread it is being called on (it won't freeze the interface if called on the main thread of your GUI application). Because the task is asynchronous, the output will usually look like this: Because the code inside of the closure, |
| Closures and Type Alias A closure can be defined with a You can then define a function using the typealias: Syntax
RemarksFor more information on Swift closures, see Apple's documentation (opens new window). |
Read Article
https://develop.horje.com/learn/1434/reference