10 Jun 2015
Get unique values in a Swift array
Get unique values in a Swift array
Recently I was working on an IOS app in Swift language. I came through an issue that I was having an array. That array was filled with values on run time. Most of values were duplicate. So I need to get a unique array. In Swift I did not findĀ a function to getĀ unique values. After some Google search I found a same type of question on Stackoverflow and the answer was the solution to my problem.
func uniq<S: SequenceType, E: Hashable where E==S.Generator.Element>(source: S) -> [E] { var seen: [E:Bool] = [:] return filter(source) { seen.updateValue(true, forKey: $0) == nil } } let a = ["four","one", "two", "one", "three","four", "four"] uniq(a) // ["four", "one", "two", "three"]
Unique values of array in swift