Understanding closures

A closure, like a function, contains a sequence of instructions and can take parameters and return values. However, closures don't have names. The sequence of instructions in a closure is surrounded by curly braces ({ }), and the in keyword separates the arguments and return type from the body.

Closures can be assigned to a constant or variable, so they're handy if you need to pass them around inside your program. For instance, let's say you have an app that downloads a file from the internet, and you need to do something to the file once it has finished downloading. You can put a list of instructions to process the file inside a closure and have your program execute it once the file finishes downloading. You'll see how closures are used in Chapter 16, Getting Started with MapKit.

Type in and run the following code:

// Closures
// var numbersList = [2, 4, 6, 7]
let myClosure = { (number: Int) -> Int in
let result = number * number
return result
}
let mappedNumbers = numbersList.map(myClosure)

This assigns a block of code that calculates a number's power of two to myClosure. The map() function then applies this closure to every element in numbersList. [4, 16, 36, 49] appears in the Results area.

It's possible to write closures in a more concise fashion and you'll see how to do that in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.130.24