Swift 中map、flatMap、compactMap、filer、reduce的使用总结
Swift相比于Objective-C又一个重要的优点,它对函数式编程提供了很好的支持,Swift提供了map、flatMap、compactMap、filer、reduce这三个高阶函数作为对容器的支持。
1.map : 可以对数组中的每一个元素做一次处理
// 计算字符串的长度 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 }) // $0代表数组中的每一个元素 stringArray.map{ return $0.count }
let arr = [1,2,3,4,5,6,7] func addOne(n1: Int) ->Int{ return n1+1; } let arr1 = arr.map(addOne) print(arr1)//[2, 3, 4, 5, 6, 7, 8]
let arr = [1,2,3,4,5,6,7] let arr1 = arr.map{(n1) in n1+1} print(arr1) //[2, 3, 4, 5, 6, 7, 8]
let arr = [1,2,3,4,5,6,7] let arr1 = arr.map{$0+1} print(arr1) //[2, 3, 4, 5, 6, 7, 8]
2.flatMap与map的区别
(1)flatMap返回后的数组中不存在nil, 同时它会把Optional解包
let array = ["Apple", "Orange", "Puple", ""] let arr1 = array.map { a -> Int? in let length = a.count guard length > 0 else { return nil } return length } arr1 // [5, 6, 5, nil] let arr2 = array.flatMap { a-> Int? in let length = a.count guard length > 0 else { return nil} return length } arr2 // [5, 6, 5]
(2)flatMap还能把多维数组变成一维数组:
let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] let arr1 = array.map{ $0 } arr1 // [[1, 2, 3], [4, 5, 6], [7, 8, 9]] let arr2 = array.flatMap{ $0 } arr2 // [1, 2, 3, 4, 5, 6, 7, 8, 9]
(3)flatMap也能把两个不同的数组合并成一个数组,这个合并的数组元素个数是前面两个数组元素个数的乘积:
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"]
4、compactMap: 当后面的闭包中返回Optional的时候,在Swift 4.1之后应该使用compactMap代替map。
5、filer:过滤,可以对数组中的元素按照某种规则进行一次过滤:
// 筛选出字符串的长度小于10的字符串 let stringArray = ["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 }
6、reduce:计算,可以对数组的元素进行计算:
// 将数组中的每个字符串用‘、’拼接 let stringArray = ["Objective-C", "Swift", "HTML", "CSS", "JavaScript"] func appendString(string1: String, string2: String) -> String { return string1 == "" ? string2 : string1 + "、" + string2 } // reduce方法中的第一个参数是初始值 stringArray.reduce("", appendString) stringArray.reduce("", {(string1, string2) -> String in return string1 == "" ? string2 : string1 + "、" + string2 }) // $0表示计算后的结果, $1表示数组中的每一个元素 stringArray.reduce("", { return $0 == "" ? $1 : $0 + "、" + $1 })