swift中高阶函数map、flatMap、filter、reduce
Swift相比于Objective-C又一个重要的优点,它对函数式编程提供了很好的支持,Swift提供了map、filter、reduce这三个高阶函数作为对容器的支持。
1 map:可以对数组中的每一个元素做一次处理
// 计算字符串的长度 let stringArray = ["Objective-C", "Swift", "HTML", "CSS", "JavaScript"] func stringCount(string: String) -> Int { return string.characters.count } stringArray.map(stringCount) stringArray.map({string -> Int in return string.characters.count }) // $0代表数组中的每一个元素 stringArray.map{ return $0.characters.count }
2 flatMap与map不同之处:
(1)flatMap返回后的数组中不存在nil,同时它会把Optional解包
let array = ["Apple", "Orange", "Puple", ""] let arr1 = array.map { a -> Int? in let length = a.characters.count guard length > 0 else { return nil } return length } arr1 // [{some 5}, {some 6}, {some 5}, nil] let arr2 = array.flatMap { a-> Int? in let length = a.characters.count guard length > 0 else { return nil} return length } arr2 // [5, 6, 5]
(2)flatMap还能把数组中存有数组的数组(二维数组、N维数组)一同打开变成一个新的数组
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"]
3 filer:过滤,可以对数组中的元素按照某种规则进行一次过滤
// 筛选出字符串的长度小于10的字符串 let stringArray = ["Objective-C", "Swift", "HTML", "CSS", "JavaScript"] func stringCountLess10(string: String) -> Bool { return string.characters.count < 10 } stringArray.filter(stringCountLess10) stringArray.filter({string -> Bool in return string.characters.count < 10 })
// $0表示数组中的每一个元素 stringArray.filter{ return $0.characters.count < 10 }
4 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 })