Map

While the filter algorithm is used to select only certain elements of an array, map is used to apply logic to all elements in the array. The following example shows how to use the map algorithm to divide each number by 10:

var arrayOne = [10, 20, 30, 40] 
let applied = arrayOne.map{ $0 / 10} 
//applied contains 1,2,3 and 4 

In the preceding code, the new array contains the numbers 1, 2, 3, and 4, which is the result of dividing each element of the original array by 10.

The new array created by the map algorithm is not required to contain the same element types as the original array; however, all the elements in the new array must be of the same type. In the following example, the original array contains integer values, but the new array created by the map algorithm contains string elements:

var arrayOne = [1, 2, 3, 4] 
let applied = arrayOne.map{ "num:($0)"} 
//applied contains "num:1", "num:2", "num:3" and "num:4" 

In the preceding code, we created an array of strings that appends the numbers from the original array to the num: string.

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

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