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:
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.
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.
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:
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.
That may be the real requirement in application code.
Common Pitfalls
- Using
Setand then being surprised that the original order changed. - Forgetting that
SetrequiresHashableelements. - Removing duplicates by equality when the real business rule is uniqueness by a specific key.
- Using repeated
containsscans on large arrays when aSet-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
seenset plusfilterwhen you need unique values in original order. - Wrap the pattern in an extension when it appears often.
- For non-
Hashabletypes, either define hashing or accept a slower equality-based scan. - Always define what “unique” means before choosing the implementation.

