Swift
Programming
Arrays
Unique Values
Coding

Unique values of array in swift

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Getting unique values from an array in Swift is easy if you only care about uniqueness and do not care about order: convert the array to a Set. If you need to preserve the original order, you need a slightly different approach because Set does not maintain insertion order.

That distinction matters more than the syntax. Many “remove duplicates” snippets are technically correct but quietly scramble the array, which may break UI output or tests.

Fastest Simple Approach: Set

For Hashable element types, the shortest solution is:

swift
let values = [1, 2, 2, 3, 1, 4]
let unique = Array(Set(values))
print(unique)

This removes duplicates efficiently, but the resulting order is not guaranteed to match the original array.

That makes it fine for membership-like operations, but risky when order matters.

Preserve Original Order

If you want the first occurrence of each element and want to keep the input order, track a Set of seen values while building a result array.

swift
1var seen = Set<Int>()
2let values = [1, 2, 2, 3, 1, 4]
3
4let uniqueInOrder = values.filter { seen.insert($0).inserted }
5print(uniqueInOrder)

This is a common Swift idiom. The inserted flag is true only the first time an element enters the set.

Make It Reusable with an Extension

If you need this often, wrap it in an array extension.

swift
1extension Array where Element: Hashable {
2    func uniqued() -> [Element] {
3        var seen = Set<Element>()
4        return self.filter { seen.insert($0).inserted }
5    }
6}
7
8let names = ["Ana", "Bob", "Ana", "Cara"]
9print(names.uniqued())

This gives you a readable API and preserves order.

What If the Elements Are Not Hashable?

If the element type is not Hashable, you cannot use a Set directly. Then you either:

  • make the type conform to Hashable
  • use a slower equality-based scan
  • choose a different key to represent uniqueness

A simple equality-based version looks like this:

swift
1struct Person: Equatable {
2    let id: Int
3    let name: String
4}
5
6let people = [
7    Person(id: 1, name: "Ana"),
8    Person(id: 2, name: "Bob"),
9    Person(id: 1, name: "Ana")
10]
11
12let uniquePeople = people.reduce(into: [Person]()) { result, person in
13    if !result.contains(person) {
14        result.append(person)
15    }
16}

This works, but it is typically slower for large arrays because contains scans the partial result repeatedly.

Choose the Right Definition of Unique

Sometimes “unique” means unique whole values. Other times it means unique by one field, such as id.

swift
1struct User {
2    let id: Int
3    let name: String
4}
5
6let users = [
7    User(id: 1, name: "Ana"),
8    User(id: 2, name: "Bob"),
9    User(id: 1, name: "Ana Updated")
10]
11
12var seenIds = Set<Int>()
13let uniqueById = users.filter { seenIds.insert($0.id).inserted }

That may be the real requirement in application code.

Common Pitfalls

  • Using Set and then being surprised that the original order changed.
  • Forgetting that Set requires Hashable elements.
  • Removing duplicates by equality when the real business rule is uniqueness by a specific key.
  • Using repeated contains scans on large arrays when a Set-based approach would be much faster.
  • Writing a one-off duplicate-removal loop everywhere instead of extracting a reusable helper.

Summary

  • 'Array(Set(values)) removes duplicates quickly but does not preserve order.'
  • Use a seen set plus filter when you need unique values in original order.
  • Wrap the pattern in an extension when it appears often.
  • For non-Hashable types, either define hashing or accept a slower equality-based scan.
  • Always define what “unique” means before choosing the implementation.

Course illustration
Course illustration

All Rights Reserved.