Swift 5.0-flatMap与compactMap

Swift 5.0 中flatMap可以将数组扁平化,实现数组降维,例如:

1.flatMap应用于序列并返回一个序列:

let results = [[2,5,7], [4,8], [1,10,3]]
let allResults = results.flatMap { $0 }
print("\(allResults)")
[2, 5, 7, 4, 8, 1, 10, 3]

可以将数组进行二次过滤:

let filters = results.flatMap { $0.filter { $0 > 5} }
[7, 8, 10]

2.flatMap应用于可选类型:
如果原始的值是nil然后flatMap返回nil:

let input: Int? = Int("10")
let opres: Int? = input.flatMap { $0 > 5 ? $0 : nil }
print("\(String(describing: opres))")
Optional(10)

3.序列可选类型,Swift 4.1之前可以使用flatMap,现在需要compactMap:

let names: [String?] = ["Fly", nil, "Elephant", nil, "FlyElephant"]
let valid = names.flatMap { $0 }
print("\(valid)")

警告提示:

'flatMap' is deprecated: Please use compactMap(_:) for the case where closure returns an optional value

修改之后的代码:

let names: [String?] = ["Fly", nil, "Elephant", nil, "FlyElephant"]
let valid = names.compactMap { $0 }
print("\(valid)")

数组中通过类型转换返回nil,也会出现警告:

let words = ["53", "FlyElephant", "hello","0"]
let values = words.flatMap { Int($0) }

compactMap替换flatMap可以移除⚠️:

let words = ["53", "FlyElephant", "hello","0"]
let values = words.compactMap { Int($0) }
print("\(values)")
[53, 0]

一般情况下map与flatMap的功能是相似的,都可以执行map工作。

compactMap的改变是在于将flatMap处理non-optional序列类型,compact处理optional类型。

参考链接:
https://useyourloaf.com/blog/replacing-flatmap-with-compactmap/

你可能感兴趣的:(Swift 5.0-flatMap与compactMap)