How to Get Rid of Duplicates in a Swift Array: A Clear Guide for Beginners
\n\nHave you ever encountered a situation where your array in Swift turned into a "dump" of repeating data? If so, you are not alone. The question "Removing duplicate elements from an array in Swift" on Stack Overflow has gathered thousands of views — and it's no surprise. Working with duplicates is one of the most common tasks every developer faces, whether a beginner or a pro. Today, we will once and for all figure out how to elegantly and efficiently remove duplicate elements from an array in Swift, using proven methods and real code examples.
\n\nWhy This Matters: Practical Scenarios
\n\nImagine you are writing a contact management application. The user imports a list of 1000 records, but 200 of them are duplicates. Or you are working with data from an API where the same product arrives multiple times. Duplicates not only clutter the interface but can also lead to logical errors, increased processing time, and data confusion. Knowing how to clean arrays is a fundamental skill that will save you hours of debugging.
\n\nIn this tutorial, we will look at several approaches: from the simple use of Set to more advanced methods that preserve element order and work with custom data types. Let's go!
Method 1: Using Set — The Fastest and Simplest Way
\n\nThe most popular answer on Stack Overflow for removing duplicates from an array in Swift is using the Set structure. Set is an unordered collection of unique elements. By converting an array to a Set, we automatically get rid of all repetitions, and then convert it back to an array.
Code Example:
\n\nlet numbers = [1, 2, 3, 2, 4, 5, 1, 3]\nlet uniqueNumbers = Array(Set(numbers))\nprint(uniqueNumbers) // Output: [5, 2, 3, 1, 4] (order may vary)\n\n\nThis method works lightning fast, especially on large arrays, because Set uses hashing. But there is one nuance: the order of elements is not preserved. If the original order is important to you, read on.
When to Use Set?
\n- \n
- When the order of elements does not matter. \n
- When you need the fastest possible solution. \n
- When working with primitive types (Int, String, Double, etc.) that conform to the
Hashableprotocol. \n
Method 2: Preserving Order with NSOrderedSet
\n\nIf you are working on a project where the Objective-C runtime is allowed (e.g., legacy projects or mixed codebases), you can use NSOrderedSet. This class from Foundation preserves the insertion order and automatically removes duplicates.
Code Example:
\n\nimport Foundation\n\nlet names = ["Anna", "Boris", "Anna", "Victor", "Boris"]\nlet uniqueNames = NSOrderedSet(array: names).array as! [String]\nprint(uniqueNames) // Output: ["Anna", "Boris", "Victor"]\n\n\nPros: order is preserved, code is short. Cons: it uses a bridge to Objective-C, which may be excessive for a pure Swift project. Additionally, NSOrderedSet is slower than the native Set due to additional overhead.
Method 3: Custom Filtering with Order Preservation (Pure Swift)
\n\nThis is the most flexible and recommended approach for modern Swift. We create an empty array for the result and a Set to track already seen elements. Iterating through the original array, we add an element to the result only if it is not already in the Set.
Code Example:
\n\nfunc removeDuplicates<T: Hashable>(from array: [T]) -> [T] {\n var seen = Set<T>()\n var result = [T]()\n \n for element in array {\n