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