map
对于原始集合里每一个元素,以一个变换后的元素替换之 行程一个新的集合
filter
对于原始集合里面的每一个元素,通过判断来将其丢弃或者放进新的集合
reduce
对于原始集合里的每一个元素,作用于当前累积的结果上
flatMap
对于元素是集合的合集,可以得到单级的集合
//: A UIKit based Playground for presenting user interface
import UIKit
let results = [[1,2,3],[4,5,6],[7,8,9]]
let allResults=results.flatMap{ $0.map{$0 * 10}}
print(allResults)
let passMarks=results.flatMap{ $0.filter {$0>5}}
print(passMarks)
[10, 20, 30, 40, 50, 60, 70, 80, 90]
[6, 7, 8, 9]
compactMap
过滤空值
//: A UIKit based Playground for presenting user interface
import UIKit
let keys:[String?] = ["Zhangsan",nil,"Lisi",nil,"WangWU"]
let vaildNames = keys.compactMap{ $0 }
print(vaildNames)
let counts = keys.compactMap{$0?.count}
print(counts)
["Zhangsan", "Lisi", "WangWU"]
[8, 4, 6]