In Swift, an array is a collection of values that can be of any type. Sometimes, you may want to print only the unique items of an array. There are different approaches you can take:
Set
to remove any duplicates, note that the order of the elements may not be preserved.let array = ["one", "one", "two", "two", "three", "three"]
let unique = Array(Set(array))
print(unique)
// Prints: ["three", "one", "two"]
Array
that filters out any duplicates while maintaining the order.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
}
}
let array = ["one", "one", "two", "two", "three", "three"]
print(array.unique)
// Prints: ["one", "two", "three"]
reduce
method: Another approach to print unique items of an array is to use the reduce
method. This method iterates over each element in the array and builds a new array containing only the unique elements.let array = ["one", "one", "two", "two", "three", "three"]
let uniqueArray = array.reduce([]) { (result, element) in
result.contains(element) ? result : result + [element]
}
print(uniqueArray)
// Prints: ["one", "two", "three"]