swift中高阶函数map、flatMap、filter、reduce

Swift相比于Objective-C又一个重要的优点,它对函数式编程提供了很好的支持,Swift提供了map、filter、reduce这三个高阶函数作为对容器的支持。

1 map:可以对数组中的每一个元素做一次处理

swift中高阶函数map、flatMap、filter、reduce

swift中高阶函数map、flatMap、filter、reduce

2 flatMap与map不同之处:

  (1)flatMap返回后的数组中不存在nil,同时它会把Optional解包

swift中高阶函数map、flatMap、filter、reduce

swift中高阶函数map、flatMap、filter、reduce

  (2)flatMap还能把数组中存有数组的数组(二维数组、N维数组)一同打开变成一个新的数组

swift中高阶函数map、flatMap、filter、reduce

swift中高阶函数map、flatMap、filter、reduce

  (3)flatMap也能把两个不同的数组合并成一个数组,这个合并的数组元素个数是前面两个数组元素个数的乘积

swift中高阶函数map、flatMap、filter、reduce

swift中高阶函数map、flatMap、filter、reduce

3 filer:过滤,可以对数组中的元素按照某种规则进行一次过滤

swift中高阶函数map、flatMap、filter、reduce

swift中高阶函数map、flatMap、filter、reduce

4 reduce:计算,可以对数组的元素进行计算

swift中高阶函数map、flatMap、filter、reduce

swift中高阶函数map、flatMap、filter、reduce

https://www.cnblogs.com/muzijie/p/6542650.html