美文网首页Swift
Swift 4.1 - SE-0187 Introduce Se

Swift 4.1 - SE-0187 Introduce Se

作者: ienos | 来源:发表于2020-12-09 11:25 被阅读0次

提供 Sequence.compactMap(_:) 替换 Sequence.flatMap


Sequence.flatMap 的功能,是在序列中过滤 nil 元素中的值,例子如下:

let possibleNumbers = ["1", "2", "three", "///4///", "5"]

let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
// [1, 2, nil, nil, 5]

let compactMapped: [Int] = possibleNumbers.flatMap { str in Int(str) }
为什么要替换掉 flatMap ?

在 Swift 标准库中定义了三种 flatMap 不同的重载

Sequence.flatMap<S>(_: (Element) -> S) -> [S.Element] where S: Sequence
Optional.flatMap<U>(_: (Wrapped) -> U?) -> U?
Sequence.flatMap<U>(_: (Element) -> U?) -> [U]
问题 1: 第三个经常使用,但是会经常被误用成 map 来使用,例如
struct Person {
    var age: Int
    var name: String
}

func getAges(people: [Persion] -> [Int]) {
    return people.flatMap { $0.age }
}
问题 2: flatMap 多个重载可能会导致编译器产生错误

因此使用 compactMap 代替,与原 flatMap 功能基本一致,旧函数 flatMap 仍可以使用(但是不建议),编译时会弹出不推荐的警告

let possibleNumbers = ["1", "2", "three", "///4///", "5"]

let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
// [1, 2, nil, nil, 5]

let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }

相关文章

网友评论

    本文标题:Swift 4.1 - SE-0187 Introduce Se

    本文链接:https://www.haomeiwen.com/subject/crqhgktx.html