Swift 3.0 简单高阶函数 —
Map
,filter
,reduce
和flatMap
笔记整理
Map
对集合进行循环,并对集合中的每个元素应用相同的操作, 然后将所有的变换后的元素组成新的集合.
例子:
普通数组映射:
var numArr = [1, 2, 3, 4, 5]
var emptyArr :[Int] = []
for num in numArr {
emptyArr.append(num * 2)
}
// emptyArr = [2, 4, 6, 8, 10]
使用map
函数写法:
var numArr = [1, 2, 3, 4, 5]
var newArr1 = numArr.map { (value) -> Int in
return value * 2
}
// newArr1 = [2, 4, 6, 8, 10]
var newArr2 = numArr.map { (value) in
return value * 2
}
// newArr2 = [2, 4, 6, 8, 10]
// 闭包中单条语句可以省略return
var newArr3 = numArr.map{value in value * 2}
// newArr3 = [2, 4, 6, 8, 10]
// $0 表示闭包第一个参数,$1以此类推
var newArr4 = numArr.map{$0 * 2}
// newArr4 = [2, 4, 6, 8, 10]
Filter
普通数组过滤:
var numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
var emptyArr : [Int] = []
for num in numArr {
if num % 2 == 0 {
emptyArr.append(num)
}
}
// emptyArr = [2,4,6,8]
使用filter
函数写法:
var numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
// filter (其他写法跟上面类似, 不再啰嗦)
let newArr = numArr.filter{$0 % 2 == 0}
// newArr = [2,4,6,8]
Reduce
普通数组求和:
let numArr = [1, 2, 3, 4, 5]
var sum : Int = 0
for num in numArr {
sum += num
}
// sum = 15
reduce
函数写法:
// reduce函数:
/* 参数:
* initialResult : 初始值
* nextPartialResult : 闭包 (上次结果, 下一个值) -> 下一次结果
*/
reduce(initialResult: Result , nextPartialResult: (Result, Int) -> Result)
let numArr = [1, 2, 3, 4, 5]
let sum = numArr.reduce(0) { (result, nextNum) -> Int in
return result + nextNum
}
// sum = 15
// 简洁写法:
let numArr = [1, 2, 3, 4, 5]
let sum = numArr.reduce(0) { $0 + $1 }
// or numArr.reduce(0, { $0 + $1 })
// sum = 15
let numArr = [1, 2, 3, 4, 5]
let sum = numArr.reduce(0, +)
// sum = 15
FlatMap
合并两个数组 普通写法:
let arrInArr = [[1,2,3],[4,5,6]]
var emptyArr : [Int] = []
for arr in arrInArr {
emptyArr += arr
}
// emptyArr = [1, 2, 3, 4, 5, 6]
flatMap
写法:
补充:
let arrInArr = [[1,2,3],[4,5,6]]
let flattendArr = arrInArr.flatMap { $0 }
// flattendArr = [1, 2, 3, 4, 5, 6]
// 过滤含optional类型值的数组
let name : [String?] = ["zhangsan",nil,"lisi",nil,"wang"]
let validName = name.flatMap{ $0 }
// validName = ["zhangsan", "lisi", "wang"]
函数链式编程
以上这些简单的例子总结了高阶函数代替更常用的方法。使用这些函数可以编写更优雅、更易于维护的代码,可读性更好。
let arrInArr = [[1,2,3],[4,5,6]]
let newValue = arrInArr.flatMap{$0}.filter{$0 % 2 == 0}.map{$0 * 2}.map{"$\($0)"}
// newValue = ["$4", "$8", "$12"]
网友评论