Append unique values to an array in swift
You can use a Set
which guarantees unique values.
var selectedValues = Set<String>()
// ...
selectedValues.insert(newString) // will do nothing if value exists
Of course, the elements of a Set
are not ordered.
If you want to keep the order, just continue with the Array
but check before you insert.
if !selectedValues.contains("Bar") { selectedValues.append("Bar") }
I guess that your problem was resolved but I add my answer for next developers who's facing same problem :)
My solution is to write an extension of Array to add elements from an array with a distinct way:
here the code :
extension Array{
public mutating func appendDistinct<S>(contentsOf newElements: S, where condition:@escaping (Element, Element) -> Bool) where S : Sequence, Element == S.Element {
newElements.forEach { (item) in
if !(self.contains(where: { (selfItem) -> Bool in
return !condition(selfItem, item)
})) {
self.append(item)
}
}
}
}
example:
var accounts: [Account]
let arrayToAppend: [Account]
accounts.appendDistinct(contentsOf: arrayToAppend, where: { (account1, account2) -> Bool in
return account1.number != account2.number
})