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?
-
Do you care about the order of the elements?Alexander– Alexander2016-11-13 23:17:29 +00:00Commented Nov 13, 2016 at 23:17
Add a comment
|
1 Answer
If you don't care about order:
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"]
If you care about the order:
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"]
7 Comments
masakih
i think, if change alreadyAdded type to Array, it will be faster.
Alexander
@masakih What makes you suspect that? Sets have
O(1) look ups (needed for fast contains(_:) calls), whereas array have O(n) loop ups in the general casemasakih
sorry! i was focusing on
insert(_:) only. but i had overlooked contains(_:).Alexander
@masakih
insert(_:) is also constant time for sets, too.masakih
i checked which fast are
Array.append(_:) and Set.insert(_:). Array.append(_:) uses half time of Set.insert(_:). of course, in this case Set is best. [swift.sandbox.bluemix.net/#/repl/58d9e75c50cb957f193a78d9] |