swift基础之高阶函数

原创
2021/04/12 16:27
阅读数 52

map

let arr = [1,2,3,4]
//map
let mapRet = arr.map{ $0 * 2 }
print(mapRet)
//[2, 4, 6, 8]

filter

//filter
let filterRet = arr.filter{ $0 % 2 == 0 }
print(filterRet)
//[2, 4]

reduce:累积操作

let reduceRet = arr.reduce(10, +)
print(reduceRet)
//20

let reduceRetTwo = arr.reduce(10, -)
print(reduceRetTwo)
//0

flatMap

使用映射函数映射每个元素,然后将结果压缩成一个新数组

//flatMap
let results = [[1,2,3], [3,4,5]]
let allResults = results.flatMap{ $0.map{ $0 * $0 } }
print(allResults)
//[1, 4, 9, 9, 16, 25]

compactMap:过滤空值

//compactMap:过滤空值
let keys: [String?] = ["zhang san", nil, "li si", nil]
let validNames = keys.compactMap{ $0 }
print(validNames)
//["zhang san", "li si"]
let keyCount = keys.compactMap{ $0?.count }
print(keyCount)
//[9, 5]
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部