Swift provides the following higher-order functions: Map, flatMap, filter, and reduce. Functional programming using higher-order functions not only simplifies our code, but is also faster than traditional implementations when the data is large because it can be executed in parallel (such as running on multiple cores).

I. Map function

  1. Methods to introduce

The map method takes a closure expression as its only argument. The closure function is called once for each element in the array and returns the value mapped to that element. In simple terms, each element of an array is converted by a method that returns a new array. 2. Use an example

(1) convert Int () to String () and concatenate “Swift”

let  ins = [2, 3, 4]
let  strs = ins.map ({  "Swift\($0)"  })
print (strs) /// ["Swift2", "Swift3", "Swift4"]
Copy the code

(2) Square an array of data

let  values = [2, 3, 4]
let  squares = values.map ({ $0 * $0 })
print (squares) ///[4, 9, 16]
Copy the code

FlatMap function

  1. Methods to introduce

The flatMap method is similar to the map method, except that it does not return nil in the array (it automatically strips out nil) and unpacks Optional. 2. Use example (1) to compare the map and flatMap methods

let  array = [ "Blue" ,  "red" ,  "Green" ,  "" ]
 
let  arr1 = array.map { a ->  Int?  in
     let  length = a.count
     guard length > 0  else  {  return  nil  }
     return  length
}
print ( "arr1:\(arr1)" )
 
let  arr2 = array.flatMap { a->  Int?  in
     let  length = a.count
     guard length > 0  else  {  return  nil  }
     return  length
}
print ( "arr2:\(arr2)" )

/// arr1:[Optional(4), Optional(3), Optional(5), nil]
/// arr2:[4, 3, 5]
Copy the code
FlatMap: Note: after 4.1 if the value returned in the closure is optional, you will need to use compactMap instead of flatMap, otherwise you will be warned. @available(swift, deprecated: 4.1, renamed: "compactMap(_:)", message: "Please use compactMap(_:) for the case where closure returns an optional value")Copy the code

(2) flatMap can also open the array containing the array (two-dimensional array, n-dimensional array) together to assemble a new array.

let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] let arr1 = array.map { $0 } let arr2 = array.flatMap{ $0 } print(arr1) print(arr2) ///[[1, 2, 3], [4, 5, 6], [7, 8, [1, 2, 3, 4, 5, 6, 7, 8, 9]Copy the code

3. Filter function

  1. Methods to introduce

The filter method is used to filter elements that meet certain criteria in an array element. 2. Use example (1) to screen out elements with an amount greater than 10.

let  prices = [2, 15, 23]
let  result = prices.filter ({ $0 > 10 })
print (result) // [15, 23]
Copy the code

Reduce function

  1. Methods to introduce

The reduce method evaluates the array element combination as a value and accepts an initial value, which can be of a different type than the array element type. (1) Add the amounts in the array and calculate the total.

Let prices = [20,30,40] let sum = price.reduce (0) {$0 + $1} // let prices = [20,30,40] let sum = price.reduce (0) {$0 + $1} //Copy the code

(2) Convert the array to a string, with each element separated by a comma (,).

let array = [ "Blue" , "red" , "Green" ] let str = array.reduce( "" , { return $0 == "" ? $1: $0 + ", "+ $1}) print (STR)/// let str2 = array.joined(separator:", ")// Blue, red, GreenCopy the code

Five, the combination of high-order functions, chain call

(1) flatMap and filter are used to filter out even numbers in multidimensional integer arrays and combine them into a one-dimensional array.

let  collections = [[2, 7, 9], [4, 1], [5, 1, 3]]
let  onlyEven = collections.flatMap {
     $0.filter  { $0 % 2 == 0 }
}
print (onlyEven) ///[2, 4]
Copy the code

(2) Map and Reduce calculate the sum of each group in a two-dimensional array.

Let the collections = [,2,7 [5], [4, 8], [9,1,3]] let sums = collections. The map ({$0. Reduce (0, +)}) print (sums) / / / [18, 5, 9]Copy the code

2, chain combination (1) sum all the numbers in the array greater than 5.

let  marks = [5, 2, 7, 3, 6, 8]
let  total = marks.filter {$0 > 5}.reduce(0,+)
print(total) /// 21
Copy the code

(2) Square the numbers in an array and filter out even values.

let  numbers = [2, 9, 5, 4, 8, 7]
let  evenSquares = numbers.map {$0 * $0}.filter {$0 % 2 == 0}
print(evenSquares) /// [4, 16, 64]
Copy the code
End
Copy the code