Basically I need a version of appendContentsOf:
which does not append duplicate elements.
Example
var a = [1, 2, 3]
let b = [3, 4, 5]
a.mergeElements(b)
//gives a = [1, 2, 3, 4, 5] //order does not matter
Simply :
let unique = Array(Set(a + b))
Swift 5 Updated
In case you need to combine multiple arrays.
func combine<T>(_ arrays: Array<T>?...) -> Set<T> {
return arrays.compactMap{$0}.compactMap{Set($0)}.reduce(Set<T>()){$0.union($1)}
}
Usage examples:
1.
let stringArray1 = ["blue", "red", "green"]
let stringArray2 = ["white", "blue", "black"]
let combinedStringSet = combine(stringArray1, stringArray2)
// Result: {"green", "blue", "red", "black", "white"}
let numericArray1 = [1, 3, 5, 7]
let numericArray2 = [2, 4, 6, 7, 8]
let numericArray3 = [2, 9, 6, 10, 8]
let numericArray4: Array<Int>? = nil
let combinedNumericArray = Array(combine(numericArray1, numericArray2, numericArray3, numericArray4)).sorted()
// Result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With