Is there any easy way to merge two arrays in swift along with removing duplicates?
Simply :
let unique = Array(Set(a + b))
This is commonly called a union, which is possible in Swift using a Set
:
let a = [1, 2, 3]
let b = [3, 4, 5]
let set = Set(a)
let union = set.union(b)
Then you can just convert the set into an array:
let result = Array(union)
Swift 4.0 Version
extension Array where Element : Equatable {
public mutating func mergeElements<C : Collection>(newElements: C) where C.Iterator.Element == Element{
let filteredList = newElements.filter({!self.contains($0)})
self.append(contentsOf: filteredList)
}
}
As mentioned: The array passed to the function is the array of object that will be omitted from the final array