How to find the Difference between two arrays in Swift

January 14, 2019

In situation where you would like all the elements that are in one array but not the other (ie in one array but not both) - a solution is to use Set. Sets have a symmetricDifference() method that does exactly this, so you just need to convert both arrays to a set, then convert the result back into an array.

Let's take a look,

extension Array where Element: Hashable {
    func difference(from other: [Element]) -> [Element] {
        let thisSet = Set(self)
        let otherSet = Set(other)
        return Array(thisSet.symmetricDifference(otherSet))
let names1 = ["Eliad", "Alex", "Tim"]
let names2 = ["Tim", "Alex", "Francesco"]
let difference = names1.difference(from: names2) // = ["Eliad", "Francesco"]