//高阶函数 map,flatMap,reduce,filter的区别
//map方法获取一个闭包表达式作为其参数,数组里面的元素每调用一次闭包,就返回闭包所映射的值
let stringArray = ["array","ios"];
let m = stringArray.map { (string) -> Int in
return string.count
}
let strs = stringArray.map { (string) -> String in
return "$\(string)"
}
let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9],nil]
let arrayNew = array.flatMap { changearray -> Array<Any> in
return changearray ?? []
}
let hm = array.flatMap { testm-> Array<Any> in
testm?.filter({ (h) -> Bool in
return h>3
}) ?? []
}
//gao j
let mapSum = array.map { mapm -> Int in //计算二维数组中每一个一维数组的值
mapm?.reduce(0, { (m1, m2) -> Int in
return m1+m2;
}) ?? 0
}
print("mapSum的值是",mapSum)
print("hm的值是",hm)
// FlatMap和Map的区别是 flatMap可以将二维数组转换成一维数组,并且不会返回数组中的nil,同时会自动解包
print("新的结果",arrayNew)
print(m);
//filter方法用于过滤元素,即筛选出数组元素中满足某些条件的元素
let prices = [20,30,40];
let result = prices.filter { (m) -> Bool in
return m > 25
}
print("筛选结果",result)
//reduce方法把数组元素组合计算为一个值,并且可以接受一个初始值,这个初始值可以和r数组中的元素类型不同
let sum = prices.reduce(80) { (n1, n2) -> Int in
return n1+n2;
}
print("计算结果",sum)
//高阶函数的链式使用
let numbers = [4,5,8,2,9,7]
let evenSquares = numbers.map { (m) -> Int in
return m*m
}.filter { h -> Bool in
return h>20
}
print("链式使用后的结果",evenSquares)
//compactMap 类型转换
let nums = [1, 2, 3, 4, 5]
let hresult = nums.compactMap { (item) -> String? in
return "\(item)"
}
print("结果是",hresult)
Swift的map,filter,reduce,flatMap,compactMap 高阶函数的使用
最新推荐文章于 2023-06-16 18:33:14 发布