How to display unique array elements using Swift?

I have a formula reconfiguring an array as an example var Array = [a,s,d,s,f,g,g,h,e] . I want to run a for loop or some other parameter that returns me a,s,d,f,g,h,e - only unique values. How can I do this using ios Swift?

+5
source share
1 answer

If you do not need order:

Just use the kit:

 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 that allows you to remove duplicate AnySequence elements while maintaining 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"] 
+10
source

Source: https://habr.com/ru/post/1259696/


All Articles