Closures in Swift are similar to that of self-contained functions organized as blocks and
called anywhere like C and Objective C languages. Constants and variable references
defined inside the functions are captured and stored in closures. Functions are considered
as special cases of closures and it takes the following three forms:
Global Functions Nested Functions Closure ExpressionsHave a name. Do not
capture any valuesHave a name. Capture
values from enclosing
functionUnnamed Closures capture
values from the adjacent
blocksClosure expressions in Swift language follow crisp, optimization, and lightweight syntax
styles which includes.
Inferring parameter and return value types from context. Implicit returns from single-expression closures. Shorthand argument names and Trailing closure syntaxSyntax
Following is a generic syntax to define closure which accepts parameters and returns a
data type:
{(parameters) -> return type in
statements
}Following is a simple example:
let studname = { println("Welcome to Swift Closures") }
studname()When we run the above program using playground, we get the following result:
Welcome to Swift ClosuresThe following closure accepts two parameters and returns a Bool value:
{(Int, Int) -> Bool in
Statement1