Swift: Remove duplicates from array
Video: Swift: Remove duplicates from array by Taught by Celeste AI - AI Coding Coach
Watch full page →Swift: Remove Duplicates from Array
In Swift, arrays can contain duplicate elements, but often you need a collection with unique values. This example demonstrates simple and efficient ways to remove duplicates from an array using built-in Swift features like sets and the `filter` method.
Code
// Example array with duplicates
let numbers = [1, 2, 3, 2, 4, 1, 5]
// Method 1: Using a Set to remove duplicates (order not guaranteed)
let uniqueNumbersSet = Array(Set(numbers))
print(uniqueNumbersSet) // Output might be [2, 4, 5, 1, 3]
// Method 2: Using filter and a Set to preserve order
var seen = Set<Int>()
let uniqueNumbersOrdered = numbers.filter { number in
if seen.contains(number) {
return false
} else {
seen.insert(number)
return true
}
}
print(uniqueNumbersOrdered) // Output: [1, 2, 3, 4, 5]
Key Points
- Using a Set removes duplicates but does not preserve the original order of elements.
- Filtering with a Set allows you to remove duplicates while maintaining the array’s order.
- The `filter` method combined with a tracking Set is an efficient way to keep unique elements in sequence.
- Converting between arrays and sets is simple and leverages Swift’s standard library for common tasks.