Swift 5 新特性之三 Dictionary支持compactMapValues

在理解新方法compactMapValues之前,建议先了解已有的方法map,filter, reduce。如有疑惑可以参看这里

Dictionary支持compactMapValues

提案出处:

https://github.com/apple/swift-evolution/blob/master/proposals/0218-introduce-compact-map-values.md

细节

首先我们来看看支持compactMapValues的动机。

Swift语言标准库已经为Array和Dictionary提供了两个很有用的函数:

  • The map(_:) 函数对Array内的元素执行一个函数,并返回一个Array。 compactMap(_:) 函数提供类似功能,但其可过滤掉值为 nil 的元素。
  • The mapValues(_:) 函数对Dictionary做类似 map(_:)的操作,但不过滤为值为nil 的部分。

由于Dictionary已有函数不支持过滤的功能,compactMapValues为此而生,结合了 compactMap(_:) 函数 和 mapValues(_:) 函数的功能。

我们来看下如何使用compactMapValues的案例:

let d: [String: String?] = ["a": "1", "b": nil, "c": "3"]
let r4 = d.compactMapValues({$0})
// r4 == ["a": "1", "c": "3"]

let ages = [
    "Mary": "42",
    "Bob": "twenty-five har har har!!",
    "Alice": "39",
    "John": "22"
]

let filteredAges = ages.compactMapValues({ Int($0) })
print(filteredAges)
// Output: ["Mary": 42, "Alice": 39, "John": 22]

结合上面的案例,compactMapValues应用的场景是对已有的未处理数据集合,通过自定义过滤条件,如过滤nil 或不符合格式的数据,从而得到期待的数据结果。

有兴趣的童鞋可以阅读下实现compactMapValues的源码

extension Dictionary {
    public func compactMapValues<T>(_ transform: (Value) throws -> T?) rethrows -> [Key: T] {
        return try self.reduce(into: [Key: T](), { (result, x) in
            if let value = try transform(x.value) {
                result[x.key] = value
            }
        })
    }
}

更多

获取更多内容请关注微信公众号豆志昂扬:

  • 直接添加公众号豆志昂扬
  • 微信扫描下图二维码;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章