High-order functions map, flatMap, filter, reduce in swift
Another important advantage of Swift compared to Objective-C is that it provides good support for functional programming. Swift provides three higher-order functions, map, filter, and reduce, as support for containers.
1 map: can process each element in the array once
// Calculate the length of the string let stringArray = ["Objective-C", "Swift", "HTML", "CSS", "JavaScript"] func stringcount(string:String) -> Int { return string.count } stringArray.map(stringcount) stringArray.map({string -> Int in return string.count }) stringArray.map{ return $0.count }
2 The difference between flatMap and map:
(1) There is no nil in the array returned by flatMap, and it will unpack the Optional at the same time
let array0 = ["Apple", "Orange", "Puple", ""] let arr01 = array0.map { a -> Int? in let length = a.count guard length > 0 else { return nil } return length } arr01 // [{some 5}, {some 6}, {some 5}, nil] let arr02 = array0.compactMap { a-> Int? in let length = a.count guard length > 0 else { return nil} return length } arr02 // [5, 6, 5](2) flatMap can also open the arrays (two-dimensional arrays, N-dimensional arrays) that contain arrays in the array together into a new array
let array1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] let arr11 = array1.map{ $0 } arr11 // [[1, 2, 3], [4, 5, 6], [7, 8, 9]] let arr12 = array1.flatMap{ $0 } arr12 // [1, 2, 3, 4, 5, 6, 7, 8, 9](3) flatMap can also combine two different arrays into one array. The number of elements in this combined array is the product of the number of elements in the previous two arrays.
let fruits = ["Apple", "Orange", "Puple"] let counts = [2, 3, 5] let array = counts.flatMap { count in fruits.map({ fruit in return fruit + " \(count)" }) } array // ["Apple 2", "Orange 2", "Puple 2", "Apple 3", "Orange 3", "Puple 3", "Apple 5", "Orange 5", "Puple 5"]3 filer: filter, you can filter the elements in the array once according to certain rules
// Filter out strings whose length is less than 10 let strArray = ["Objective-C", "Swift", "HTML", "CSS", "JavaScript"] func stringCountLess10(string: String) -> Bool { return string.count < 10 } stringArray.filter(stringCountLess10) stringArray.filter({string -> Bool in return string.count < 10 }) // $0表示数组中的每一个元素 stringArray.filter{ return $0.count < 10 }
4 reduce:计算,可以对数组的元素进行计算
// 将数组中的每个字符串用‘、’拼接 let strArray1 = ["Objective-C", "Swift", "HTML", "CSS", "JavaScript"] func appendString(string1: String, string2: String) -> String { return string1 == "" ? string2 : string1 + "、" + string2 } // reduce方法中的第一个参数是初始值 strArray1.reduce("", appendString) strArray1.reduce("", {(string1, string2) -> String in return string1 == "" ? string2 : string1 + "、" + string2 }) // $0表示计算后的结果, $1表示数组中的每一个元素 strArray1.reduce("", { return $0 == "" ? $1 : $0 + "、" + $1 })