能接受函数作为参数或者返回值为函数的函数,就是高阶函数
1.map(映射)
//定义一个数组,用map来遍历,并且把返回值重新组合成arr
var a = [1,2,3,4,5]
a = a.map{$0*$0}
print("a===\(a)")
//flatMap把二维数组降低为一维数组
let b = [[1, 2, 3], [1, 2, 3]]
let c = b.flatMap{$0}
print("c===\(c)")
//compactMap把数组中的可选值去掉,保留确定值
let arr = [1, 2, 3, Optional(9), nil, 4, 5]
print("arr===\(arr)")
let newArr = arr.compactMap { $0 }
print("newArr===\(newArr)")
a===[1, 4, 9, 16, 25]
c===[1, 2, 3, 1, 2, 3]
arr===[Optional(1), Optional(2), Optional(3), Optional(9), nil, Optional(4), Optional(5)]
newArr===[1, 2, 3, 9, 4, 5]
- reduce
let abc = [1,2,3,4,5]
let abd = abc.reduce(0) { (value1, value2) -> Int in
print("1==\(value1) 2===\(value2)")
return value1 + value2
}
print(abd)
1==0 2===1
1==1 2===2
1==3 2===3
1==6 2===4
1==10 2===5
15
可以看到reduce接受一个参数0,并且把闭包里返回的值作为参数继续传入reduce,闭包里value1是reduce接受的第一个参数,value2是数组的下一个元素,当元素结束的时候,整个函数返回闭包的计算值
- filter 数组过滤
let strArr = ["张三", "李四", "王五", "赵六"]
let str = strArr.filter { (str) -> Bool in
return str.hasPrefix("张")
}
print(str)
["张三"]
4.sorted数组排序
let strArr = ["张三", "李四", "王五", "赵六"]
let str = strArr.sorted {
return $0 > $1
}
print(str)
["赵六", "王五", "李四", "张三"]