[Swift] 利用 merging 來合併兩個 Dictionary

在 Swift 4 出世前,以前我們要合併兩個 Dictionary 要用 for 迴圈,並搭配 updateValue 來合併兩個 Dictionary。而在 Swift 4 之後,我們要合併兩個 Dictionary 是相當容易的,只要利用原生的 merging 函式就可以啦,怎麼用呢?來看一下範例吧

swift 1

直接給大家上範例。

let dictionary = ["a": 1, "b": 2]
let newKeyValues = zip(["a", "b"], [3, 4])

let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current }
// ["b": 2, "a": 1]
let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new }
// ["b": 4, "a": 3]

而這邊的 Current 是代表前一個數值,new 是代表合併後的數值。

所以,以一個需要展開縮合的 tableview 來說,我們可以寫成以下。

private let expandedIndexPathSubject = CurrentValueSubject<[IndexPath: Bool], Never>([:])

let didTapToggleExpand: AnyPublisher<IndexPath, Never>
didTapToggleExpand
.map { [self] item in
    expandedIndexPathSubject.value.merging([item: !(expandedIndexPathSubject.value[item] ?? false)]) { $1 }
}
.subscribe(expandedIndexPathSubject)
.store(in: &cancellables)

是不是非常 easy 呢?

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *