How to display unique elements of an array using Swift? [duplicate] How to display unique elements of an array using Swift? [duplicate] arrays arrays

How to display unique elements of an array using Swift? [duplicate]


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"]