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
            }
        })
    }
}

更多

獲取更多內容請關注微信公衆號豆志昂揚:

  • 直接添加公衆號豆志昂揚
  • 微信掃描下圖二維碼;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章