Last active
February 20, 2020 12:15
-
-
Save dotWasim/908803c3baea4116ecc672e9f9b93a11 to your computer and use it in GitHub Desktop.
Unique values of Array of items
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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