map函数:通过执行闭包中定义的操作,返回一个新的集合
使用场景: Int数组->String数组
func map() {
let nums = [1,2,3,4]
let numToStings = nums.map {"\($0)"}
print("\(numToStings)") // 打印结果["1", "2", "3", "4"]
}
flatMap函数:
使用场景1:flatmap函数用于多维数组
func flatMap() {
let arr = [[1,2,3],[3,4,5]]
let nArr = arr.flatMap {$0}
print(nArr) // 打印结果:[1, 2, 3, 3, 4, 5]
}
使用场景2:flatmap函数用于去除nil,并进行解包 (4.1之后废弃,使用compactMap代替)
func flatMap() {
let oNums:[Int?] = [0,2,4,nil,9]
let nNums = oNums.flatMap {$0}
print("\(nNums)") // 打印结果:[0, 2, 4, 9]
}
Tip:map和flatmap之间的区别在于,flatmap可对多维数组进行“降维”变为一维数组,而且可以过滤掉空值并且进行解包操作。若想要更详细的了解,可以移驾 map和flatMap之间区别相关文章 讲的很详细哦!
filter函数:用于过滤数组中符合闭包条件的元素
使用场景:
func filter() {
let nums = [1,3,5,7,9,10,13]
let filterResults = nums.filter{ $0 % 2 == 0}
print(filterResults) // 打印结果:[10]
}
reduce函数:用于求和
使用场景:对一组数值进行求和运算
func reduce() {
let arr = [1, 2, 4]
let reduceResult = arr.reduce(0) {
(p: Int, e: Int) in
return p + e
}
print(reduceResult) // 打印结果:7
}