Swift中的高阶函数:sorted, map, reduce, forEach, flatMap, filter
高阶函数(Higher-order function)
在数学和计算机科学中,高阶函数是至少满足下列一个条件的函数:
- 接受一个或多个函数作为输入
- 输出一个函数
函数式编程中,高阶函数比较常见了。
注:
$0
,$1
,$2
… 表示闭包第一个参数,第二个参数,第三个参数…。 详细可参考以撸代码的形式学习Swift-7:闭包(Closure)
1 sorted
根据给定的条件(一个用于比较的闭包)来对数组进行排序。
函数原型:
|
|
2 map
返回一个包含对原数组每个元素进行给定闭包处理后元素的数组。(也就是每个元素进行相同处理)
函数原型:
|
|
3 reduce
Returns the result of combining the elements of the sequence using the given closure.( 返回使用给定闭包组合序列元素的结果。)
函数原型:
|
|
|
|
4 forEach
Calls the given closure on each element in the sequence in the same order as a for-in loop.(与for-in
类似)
函数原型:
|
|
5 flatMap
Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.(返回一个数组,其中包含使用此序列的每个元素调用给定转换的连接结果。)
函数原型:
|
|
flatMap和map的区别是,对二维数组时flatMap有个降维处理,对于一位数组,两者没有明显区别
|
|
注:新版Swift使用了
Sequence.compactMap(_:)
来替代Sequence.flatMap
,详细
6 filter
Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.(返回一个数组,该数组按顺序包含满足给定闭包的序列元素。)
函数原型:
|
|
playground文件在andyRon/LearnSwift
文章作者 andyron
上次更新 2024-07-16
许可协议 原创文章,如需转载请注明文章作者和出处。谢谢!