find the difference of two maps in swift

Here's an extension function on Dictionary in Swift that takes in another dictionary and returns the difference between the two:

main.swift
extension Dictionary where Key: Hashable, Value: Equatable {
    func difference(from dictionary: [Key: Value]) -> [Key: Value] {
        var result = [Key: Value]()
        
        for (key, value) in self {
            if dictionary[key] != value {
                result[key] = value
            }
        }
        
        return result
    }
}
351 chars
14 lines

You can use this function to find the difference between two maps like this:

main.swift
let map1 = ["a": 1, "b": 2, "c": 3]
let map2 = ["a": 1, "b": 5, "d": 4]

let diff = map1.difference(from: map2)
// Output: ["b": 2, "c": 3]
140 chars
6 lines

In this example, the output is ["b": 2, "c": 3] because map1 has a different value for the key "b" compared to map2, and map1 also has a key "c" that is not in map2.

gistlibby LogSnag