I have a formula retuning an array as example var Array = [a,s,d,s,f,g,g,h,e]
. What I want is to run a for
loop or some other option that gives me back a,s,d,f,g,h,e
- only the unique values. How can I do this with ios Swift?
Simply use a set:
let set: Set = ["a", "s", "d", "s", "f", "g" , "g", "h", "e"]
print(set) // ["a", "s", "f", "g", "e", "d", "h"]
Use this extension, which allows you to remove duplicate elements of any Sequence
, while preserving order:
extension Sequence where Iterator.Element: Hashable {
func unique() -> [Iterator.Element] {
var alreadyAdded = Set<Iterator.Element>()
return self.filter { alreadyAdded.insert($0).inserted }
}
}
let array = ["a", "s", "d", "s", "f", "g" , "g", "h", "e"]
let result = array.unique()
print(result) // ["a", "s", "d", "f", "g", "h", "e"]
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