Swift Closures
Introduction Closures in Swift are similar to blocks in C and Objective-C and lambdas in other programming languages. Definition : Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures can capture and store references to any constants ...
Introduction
Closures in Swift are similar to blocks in C and Objective-C and lambdas in other programming languages.
Definition : Closures are self-contained blocks of functionality that can be passed around and used in your code.
Closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you. Swift’s closure expressions have a clean, clear style, with optimizations that encourage brief, clutter-free syntax in common scenarios. These optimizations include:
- Defining a closure
- Shorthand argument names
- Capturing Values and Reference Types
Defining a closure
Closures are typically enclosed in curly braces { } and are defined by a function type () -> (), where -> separates the arguments and the return type, followed by the in keyword which separates the closure header from its body.
{ (params) -> returnType in statements }
An example could be the map function applied to an Array:
let listOfName = [“dina”, “prema”, “belash”] listOfName.map({ (listOfName: String) -> String in "(listOfName) has been trained!" })
Closure expression syntax can use constant parameters, variable parameters, and inout parameters. Default values cannot be provided. Variadic parameters can be used if you name the variadic parameter. Tuples can also be used as parameter types and return types.
The example below shows a closure expression version of the backwards (: