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?
Use a dictionary like var unique = [<yourtype>:Bool]() and fill in the values like unique[<array value>] = true in a loop. Now unique.
A set is a collection of unordered unique values. Therefore, it cannot contain a duplicate element.
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.
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"]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With