Mastering macOS Programming
上QQ阅读APP看书,第一时间看更新

Map with arrays

The map function is simply the equivalent of looping through a collection (an Array, Set, or Dictionary object), applying a function to each element, adding the result of that function application to a new array, and returning that array once the iterations are complete.

So here are two ways to derive one Array object from another. First, an algorithm that will be familiar to most readers:

let units = [0,1,2,3,4,5,6,7,8,9] 

func timesTen() -> [Int]
{
var result: [Int] = []
for i in units
{
result.append(i * 10)
}
return result
}

We'll pass the units array to the timesTen function:

let tens = tensFunc() 

However, we can condense both the function implementation and the line of code that calls it to a single line, using map:

let tens = units.map({$0 * 10}) 

This essentially means take each element, apply the closure code to it, and add it to the array that is returned. The units array remains unchanged.

The resulting tens is the same in each case, but the map syntax automatically performs the iteration through the array and returns the new array.

The map function does not necessarily return an array of the same type as the array on which it is called:

let strings = units.map {"\($0)"} 

Here we map the units array of Int objects to an array of String objects.

Note that map is defined as a method of Array type objects. The same is true for Set and Dictionary types.

This makes the code significantly more concise where the implementation of the closure is only a small number of lines long.

There is a special case of map, called flatmap, with which we can unpack an Array of Array objects, combining them into a single Array:

let unitsAndTens = [units, tens] 
let flatUnitsAndTens = unitsAndTens.flatMap({$0})

Running this code will produce an array of Int objects from an array of [Int] arrays.