10

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?

1
  • Do you care about the order of the elements? Commented Nov 13, 2016 at 23:17

1 Answer 1

19

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"]
Sign up to request clarification or add additional context in comments.

7 Comments

i think, if change alreadyAdded type to Array, it will be faster.
@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 case
sorry! i was focusing on insert(_:) only. but i had overlooked contains(_:).
@masakih insert(_:) is also constant time for sets, too.
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]
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.