Fork me on GitHub

Swift closures and functions

Closures in Swift are similar to blocks in C and Objective-C.
Closures are first-class objects, so that they can be nested and passed around (as do blocks in Objective-C).
In Swift, functions are just a special case of closures.

Defining a function:

You define a function with the func keyword. Functions can take and return none, one or multiple parameters (tuples).
Return values follow the -> sign.
func jediGreet(name: String, ability: String) -> (farewell: String, mayTheForceBeWithYou: String) {
  return ("Good bye, \(name).", " May the \(ability) be with you.")

Calling a function:

let retValue = jediGreet("old friend", "Force")

Function types

Every function has its own function type, made up of the parameter types and the return type of the function itself.
For example the following function:
func sum(x: Int, y: Int) -> (result: Int) { return x + y }
has a function type of:
(Int, Int) -> (Int)
Function types can thus be used as parameters types or as return types for nesting functions.

Passing and returning functions

The following function is returning another function as its result which can be later assigned to a variable and called.
func jediTrainer () -> ((String, Int) -> String) {
  func train(name: String, times: Int) -> (String) {
    return "\(name) has been trained in the Force \(times) times"
  return train
let train = jediTrainer()
train("Obi Wan", 3)

Variadic functions

Variadic functions are functions that have a variable number of arguments (indicated by ... after the argument's type) that can be accessed into their body as an array.
func jediBladeColor (colors: String...) -> () {
  for color in colors {

{()->() in}

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
An example could be the map function applied to an Array:
let padawans = ["Knox", "Avitla", "Mennaus"]{
  (padawan: String) -> String in
  "\(padawan) has been trained!"

Closures with known types:

When the type of the closure's arguments are known, you can do as follows:
func applyMutliplication(value: Int, multFunction: Int -> Int) -> Int {
  return multFunction(value)

applyMutliplication(2, {value in
  value * 3

Closures shorthand argument names:

Closure arguments can be references by position ($0, $1, ...) rather than by name
applyMutliplication(2, {$0 * 3})
Furthermore, when a closure is the last argument of a function, parenthesis can be omitted as such:
applyMutliplication(2) {$0 * 3}

This site is not in any way intended to be an exhaustive list of all the features provided by functions and closures in Swift.
For further information please check Apple's official documentation.