Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique values of array in swift [duplicate]

Tags:

ios

swift

I'm building an iOS app with swift and i need to get all unique values of array of strings.

I've been reading the apple developer docs but it doesn't seem to have a function for it.

Can someone give me an hint?

like image 917
user3806505 Avatar asked Dec 23 '14 16:12

user3806505


People also ask

How do you make an array unique in Swift?

Use a dictionary like var unique = [<yourtype>:Bool]() and fill in the values like unique[<array value>] = true in a loop. Now unique.

Can set have duplicate values Swift?

A set is a collection of unordered unique values. Therefore, it cannot contain a duplicate element.

How do you find the unique value of an array?

To find a unique array and remove all the duplicates from the array in JavaScript, use the new Set() constructor and pass the array that will return the array with unique values.


2 Answers

There might be a more efficient way, but an extension would probably be most straightforward:

extension Array where Element: Equatable {     var unique: [Element] {         var uniqueValues: [Element] = []         forEach { item in             guard !uniqueValues.contains(item) else { return }             uniqueValues.append(item)         }         return uniqueValues     } } 

If order doesn't matter and objects are also hashable:

let array = ["one", "one", "two", "two", "three", "three"] // order NOT guaranteed let unique = Array(Set(array)) // ["three", "one", "two"] 
like image 71
Logan Avatar answered Nov 08 '22 00:11

Logan


There isn't a function to do this in the Swift standard library, but you could write one:

extension Sequence where Iterator.Element: Hashable {     func unique() -> [Iterator.Element] {         var seen: [Iterator.Element: Bool] = [:]         return self.filter { seen.updateValue(true, forKey: $0) == nil }     } }  let a = ["four","one", "two", "one", "three","four", "four"] a.unique // ["four", "one", "two", "three"] 

This has the downside of requiring the contents of the sequence to be hashable, not just equatable, but then again most equatable things are, including strings.

It also preserves the original ordering unlike, say, putting the contents in a dictionary or set and then getting them back out again.

like image 36
Airspeed Velocity Avatar answered Nov 07 '22 22:11

Airspeed Velocity