Swift高阶函数
========================
map
map
map
对于原始集合里的每一个元素, 以一个变换后的元素替换之形成一个新的集合
| let results = [1, 2, 3, 4, 5, 6, 7, 8, 9] let allResults = results.map{ $0.map{ $0 * 10 } }
print(allResults)
|
输出结果
1
| [10, 20, 30, 40, 50, 60, 70, 80, 90]
|
flatMap
flatMap
对于元素是集合的集合, 可以得到单级的集合
1 2 3 4 5 6
| let results = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] let allResults = results.flatMap{ $0.map{ $0 * 10 } } let passMarks = results.flatMap{ $0.filter{ $0 > 5 } }
print(allResults) print(passMarks)
|
输出结果
1 2
| [10, 20, 30, 40, 50, 60, 70, 80, 90] [6, 7, 8, 9]
|
compactMap
compactMap
过滤空值
1 2 3 4 5 6
| let keys: [String?] = ["Zhangsan", nil, "Lisi", nil, "Wawngwu"] let validNames = keys.compactMap{ $0 } print(validNames)
let counts = keys.compactMap { $0?.count } print(counts)
|
输出结果:
1 2
| ["Zhangsan", "Lisi", "Wawngwu"] [8, 4, 7]
|
filter
filter
对于原始集合里的每一个元素, 通过判定来将其丢弃或者放进新集合
1 2
| let numbers: [Int] = [10, 20, 30, 40, 50, 60, 70, 80, 90] print(numbers.filter{ $0 > 50})
|
输出结果
reduce
reduce
对于原始集合里的每一个元素, 作用与当前累积的结果上
1 2
| let numbers: [Int] = [1, 2, 3, 4, 5, 10] print(numbers.reduce(0) { $0 + $1 })
|
输出结果