如何深入合并2个Swift词典

时间:2015-10-04 04:17:44

标签: swift dictionary

我的问题很简单,我想知道如何深入合并2个Swift词典(不是NSDictionary)。

let dict1 = [
    "a": 1,
    "b": 2,
    "c": [
        "d": 3
    ],
    "f": 2
]

let dict2 = [
    "b": 4,
    "c": [
        "e": 5
    ],
    "f": ["g": 6]
]

let dict3 = dict1.merge(dict2)

/* Expected:

dict3 = [
    "a": 1,
    "b": 4,
    "c": [
        "d": 3,
        "e": 5
    ],
    "f": ["g": 6]
]

*/

dict1dict2具有相同的键时,我希望替换该值,但如果该值是另一个字典,我希望它可以递归合并。

这是我想要的解决方案:

protocol Mergeable {

    mutating func merge(obj: Self)

}

extension Dictionary: Mergeable {

    // if they have the same key, the new value is taken
    mutating func merge(dictionary: Dictionary) {
        for (key, value) in dictionary {
            let oldValue = self[key]

            if oldValue is Mergeable && value is Mergeable {
                var oldValue = oldValue as! Mergeable
                let newValue = value as! Mergeable

                oldValue.merge(newValue)

                self[key] = oldValue
            } else {
                self[key] = value
            }
        }
    }

}

但它给了我错误Protocol 'Mergeable' can only be used as a generic constraint because it has Self or associated type requirements

修改 我的问题与Swift: how to combine two Dictionary instances?不同,因为那个问题不是深度合并。

使用该解决方案,它将产生:

dict3 = [
    "a": 1,
    "b": 4,
    "c": [
        "e": 5
    ]
]

3 个答案:

答案 0 :(得分:2)

在我看来,这个问题是不连贯的。这是 答案,但是:

func deepMerge(d1:[String:AnyObject], _ d2:[String:AnyObject]) -> [String:AnyObject] {
    var result = [String:AnyObject]()
    for (k1,v1) in d1 {
        result[k1] = v1
    }
    for (k2,v2) in d2 {
        if v2 is [String:AnyObject], let v1 = result[k2] where v1 is [String:AnyObject] {
            result[k2] = deepMerge(v1 as! [String:AnyObject],v2 as! [String:AnyObject])
        } else {
            result[k2] = v2
        }
    }
    return result
}

以下是您的测试用例:

    let dict1:[String:AnyObject] = [
        "a": 1,
        "b": 2,
        "c": [
            "d": 3
        ]
    ]

    let dict2:[String:AnyObject] = [
        "b": 4,
        "c": [
            "e": 5
        ]
    ]
    let result = deepMerge(dict1, dict2)
    NSLog("%@", result)
    /*
    {
        a = 1;
        b = 4;
        c =     {
            d = 3;
            e = 5;
        };
    }
    */

答案 1 :(得分:1)

如何手动完成。

func += <KeyType, ValueType> (inout left: Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) { 
    for (k, v) in right { 
        left.updateValue(v, forKey: k) 
    } 
}

您还可以尝试ExSwift Library

答案 2 :(得分:1)

extension Dictionary {
    mutating func deepMerge(_ dict: Dictionary) {
        merge(dict) { (current, new) in
            if var currentDict = current as? Dictionary, let newDict = new as? Dictionary {
                currentDict.deepMerge(newDict)
                return current
            }
            return new
        }
    }
}

如何使用/测试:

var dict1: [String: Any] = [
    "a": 1,
    "b": 2,
    "c": [
        "d": 3
    ],
    "f": 2
]

var dict2: [String: Any] = [
    "b": 4,
    "c": [
        "e": 5
    ],
    "f": ["g": 6]
]

dict1.deepMerge(dict2)

print(dict1)