Game Development Reference
In-Depth Information
Closures
Closures in Swift are self-contained blocks of functionality that can be passed to other
functions or closures to be executed by the receiver. They are similar to Objective-C
blocks. The syntax is just a little easier to read. You can think of closures as functions with
no name. Closures have the following syntax:
{(parameters) - > return type in
// implementation
}
A closure starts with an opening brace (
{
) followed by a list of parameters in parentheses.
After the parameter list you see the return type symbol (
->
) with the return type followed
by the keyword
in
. After the
in
, you have the implementation of the closure and finally
a closing brace (
}
). The following code shows an example of a closure:
{ (num1: Int, num2: Int) -> Int in
return num1 + num2
}
This code will look familiar. It is the
add()
function from earlier converted to a closure.
It takes two
Int
s and returns an
Int
. To use a closure, you can pass it as a parameter to
another function.
func performOperation(num1: Int, num2: Int,
mathClosure: (Int, Int) ->Int) ->Int{
return mathClosure(num1, num2)
}
var result = performOperation(5, 6, {
(num1: Int, num2: Int) -> Int in
return num1 + num2
}
)
println("The result is : \(result)")
Here you have the
performOperation()
function from the previous section. The
only thing different about this function is the last parameter has been renamed to
math-
Closure
. Next you invoke this function, passing it two numbers and the closure, and
store the results in the variable results. Finally, you print the results to the console.