Removing Duplicates from an Array in Swift: A Tutorial for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

How to Get Rid of Duplicates in a Swift Array: A Clear Guide for Beginners

\n\n

Have 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\n

Why This Matters: Practical Scenarios

\n\n

Imagine 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\n

In 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!

\n\n

Method 1: Using Set — The Fastest and Simplest Way

\n\n

The 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.

\n\n

Code Example:

\n\n
let 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\n

This 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.

\n\n

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 Hashable protocol.
  • \n
\n\n

Method 2: Preserving Order with NSOrderedSet

\n\n

If 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.

\n\n

Code Example:

\n\n
import 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\n

Pros: 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.

\n\n

Method 3: Custom Filtering with Order Preservation (Pure Swift)

\n\n

This 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.

\n\n

Code Example:

\n\n
func removeDuplicates<T: Hashable>(from array: [T]) -> [T] {\n    var seen = Set<T>()\n    var result = [T]()\n    \n    for element in array {\n                

Blogs

Book Recommendations