Swift高阶函数


Swift高阶函数

========================

map

map

map对于原始集合里的每一个元素, 以一个变换后的元素替换之形成一个新的集合

let results = [1, 2, 3, 4, 5, 6, 7, 8, 9]
let allResults = results.map{ $0.map{ $0 * 10 } }

print(allResults)

输出结果

[10, 20, 30, 40, 50, 60, 70, 80, 90]

flatMap

flatMap对于元素是集合的集合, 可以得到单级的集合

let results = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let allResults = results.flatMap{ $0.map{ $0 * 10 } }
let passMarks = results.flatMap{ $0.filter{ $0 > 5 } }

print(allResults)
print(passMarks)

输出结果

[10, 20, 30, 40, 50, 60, 70, 80, 90]
[6, 7, 8, 9] 

compactMap

compactMap过滤空值

let keys: [String?] = ["Zhangsan", nil, "Lisi", nil, "Wawngwu"]
let validNames = keys.compactMap{ $0 }
print(validNames)

let counts = keys.compactMap { $0?.count }
print(counts)

输出结果:

["Zhangsan", "Lisi", "Wawngwu"]
[8, 4, 7]

filter

filter对于原始集合里的每一个元素, 通过判定来将其丢弃或者放进新集合

let numbers: [Int] = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(numbers.filter{ $0 > 50})

输出结果

[60, 70, 80, 90]

reduce

reduce对于原始集合里的每一个元素, 作用与当前累积的结果上

let numbers: [Int] = [1, 2, 3, 4, 5, 10]
print(numbers.reduce(0) { $0 + $1 })

输出结果

25

文章作者: 张赛东
文章链接: https://zsd.name
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 张赛东 !
评论
  目录