How to print unique items of a array in Swift

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:

  1. Using a Set: To print unique items of an array in Swift, you can use a 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"]
  1. Using an extension: If you want to keep the original order, you can use an extension on 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"]
  1. Using 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"]