我試圖弄清楚如何使用 Swift Dictionary 的“合并”功能。我對檔案感到困惑,我想要一些幫助來理解如何閱讀它。
https://developer.apple.com/documentation/swift/dictionary/3127173-merging
在檔案中,API 宣告如下所示:
func merging(_ other: [Key : Value], uniquingKeysWith
combine: (Value, Value) throws -> Value) rethrows -> [Key : Value]
它明確表明閉包有一個標簽“uniquingKeysWith”,但是,檔案中的示例根本沒有參考該閉包引數標簽!實際上這個例子似乎忽略了很多API宣告(比如回傳值)。
let dictionary = ["a": 1, "b": 2]
let otherDictionary = ["a": 3, "b": 4]
let keepingCurrent = dictionary.merging(otherDictionary)
{ (current, _) in current }
// ["b": 2, "a": 1]
let replacingCurrent = dictionary.merging(otherDictionary)
{ (_, new) in new }
// ["b": 4, "a": 3]
我想在閉包中進行每個鍵的處理,這個例子并不表明是可能的。具體來說,我想洗掉 nil 值,并用非 nil 值otherDictionary覆寫值。dictionary
我想我想過濾,并且實際上filter() otherDictionary可以在將 KVP 交給merge函式之前洗掉具有 nil 值的鍵,但如果可能的話,我寧愿只在一個閉包中進行。
uj5u.com熱心網友回復:
檔案很清楚。它說
... 使用遇到的任何重復鍵的當前值和新值呼叫 combine 閉包。
只有出現在兩個字典中的鍵才會在閉包中被處理。
在此示例中,為鍵呼叫閉包a,并分別回傳(representing ) 和(representing )b的較高值。currentdictionarynewotherDictionary
let dictionary = ["a": 1, "b": 4, "c": 4]
let otherDictionary = ["a": 3, "b": 2, "d": 5]
let keepingHighest = dictionary.merging(otherDictionary)
{ (current, new) in
print(current, new) // prints 4 2 and 1 3
return max(current, new)
}
// ["c": 4, "b": 4, "d": 5, "a": 3]
nil字典中的值正在與系統作斗爭,因為根據定義,nil值表示缺少鍵。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441303.html
標籤:迅速
