Skip to content

Instantly share code, notes, and snippets.

@dotWasim
Last active February 20, 2020 12:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dotWasim/908803c3baea4116ecc672e9f9b93a11 to your computer and use it in GitHub Desktop.
Save dotWasim/908803c3baea4116ecc672e9f9b93a11 to your computer and use it in GitHub Desktop.
Unique values of Array of items
import Foundation
let test = [1,2,3,4,1,2,2,5,20,2,1,7]
// 1- if order of items is important:
extension Sequence where Element: Hashable {
func unique() -> [Element] {
var seen: Set<Element> = []
return filter { seen.insert($0).inserted }
}
}
test.unique()
// 3- or using NSOrderedSet
Array(NSOrderedSet(array: test))
// 2- if order of items is not important, you can simply use
Array(Set(test))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment