Short answer

To remove duplicates and keep the original order, filter the array while remembering what you've seen in a Set: var seen = Set<Element>(); return filter { seen.insert($0).inserted }. Don't use Array(Set(array)) if order matters: it came out in a different order on two runs of the same program. To remove duplicates by one property, such as an email address, put that property in the set instead.

SWIFT TIPS · SWIFT

First posted on September 11, 2018 for Swift 4.2, as "[ARRAY] Remove Duplicate Array". Rewritten on November 17, 2026. All code and output below was run on a Mac with Swift 6.2.3 (Xcode 26.2) on macOS 26.0.1, built with swiftc -O. It wasn't run on iOS.

The 2018 post had an array, ["a","a","a","b","b","c","c","e","f","c"], and a GitHub Gist that removed the duplicates. The Gist's extension filtered the array and used a [Element: Bool] dictionary to remember which elements it had already added. That was a good answer: it keeps the first of each element, in the original order, and it doesn't slow down on big arrays.

The version below is the same idea with a Set, which is what the dictionary was standing in for, plus two things I've needed since: removing duplicates by a property, and knowing which shortcuts break the order.

The code

import Foundation

extension Sequence where Element: Hashable {
    /// Keeps the first occurrence of each element, in the original order.
    func uniqued() -> [Element] {
        var seen = Set<Element>()
        return filter { seen.insert($0).inserted }
    }
}

extension Sequence {
    /// Keeps the first element for each key, in the original order.
    func uniqued<Key: Hashable>(by key: (Element) -> Key) -> [Element] {
        var seen = Set<Key>()
        return filter { seen.insert(key($0)).inserted }
    }
}

let letters = ["a", "a", "a", "b", "b", "c", "c", "e", "f", "c"]
print("uniqued:      ", letters.uniqued())
print("Array(Set(...)):", Array(Set(letters)))
print("sorted Set:   ", Set(letters).sorted())
print("NSOrderedSet: ", NSOrderedSet(array: letters).array as! [String])

struct Contact { let email: String; let name: String }
let contacts = [
    Contact(email: "ana@example.com", name: "Ana"),
    Contact(email: "budi@example.com", name: "Budi"),
    Contact(email: "ANA@example.com", name: "Ana (work)"),
]
print("by email:     ", contacts.uniqued(by: { $0.email }).map(\.name))
print("by lowercased:", contacts.uniqued(by: { $0.email.lowercased() }).map(\.name))

// Timing: Set-based filter against a contains() loop
func containsLoop(_ xs: [Int]) -> [Int] {
    var out: [Int] = []
    for x in xs where !out.contains(x) { out.append(x) }
    return out
}
for n in [1_000, 10_000, 40_000] {
    let data = (0..<n).map { _ in Int.random(in: 0..<(n / 2)) }
    var t = Date()
    let a = data.uniqued()
    let setTime = Date().timeIntervalSince(t)
    t = Date()
    let b = containsLoop(data)
    let loopTime = Date().timeIntervalSince(t)
    precondition(a == b)
    print(String(format: "n=%6d  unique=%6d  Set filter %.4fs  contains loop %.4fs", n, a.count, setTime, loopTime))
}

What it printed

uniqued:       ["a", "b", "c", "e", "f"]
Array(Set(...)): ["c", "f", "e", "a", "b"]
sorted Set:    ["a", "b", "c", "e", "f"]
NSOrderedSet:  ["a", "b", "c", "e", "f"]
by email:      ["Ana", "Budi", "Ana (work)"]
by lowercased: ["Ana", "Budi"]
n=  1000  unique=   420  Set filter 0.0001s  contains loop 0.0001s
n= 10000  unique=  4354  Set filter 0.0004s  contains loop 0.0168s
n= 40000  unique= 17311  Set filter 0.0033s  contains loop 0.1696s

I ran the same program a second time. The first two lines of that run were:

uniqued:       ["a", "b", "c", "e", "f"]
Array(Set(...)): ["a", "c", "f", "e", "b"]
sorted Set:    ["a", "b", "c", "e", "f"]
NSOrderedSet:  ["a", "b", "c", "e", "f"]
by email:      ["Ana", "Budi", "Ana (work)"]
by lowercased: ["Ana", "Budi"]
n=  1000  unique=   427  Set filter 0.0001s  contains loop 0.0001s
n= 10000  unique=  4325  Set filter 0.0004s  contains loop 0.0094s
n= 40000  unique= 17281  Set filter 0.0016s  contains loop 0.1313s

Reading the results

A Set doesn't keep any order

Array(Set(letters)) removed the duplicates, but the order was c, f, e, a, b in the first run and a, c, f, e, b in the second. Nothing in the code changed. Swift randomizes the hashing for each run of a program, so the order you get from a Set can change every time the app starts. If a test or a screen happens to pass with that order, it can fail on the next launch.

Sorting the set gives a stable order, a, b, c, e, f, but it's sorted order, not the original. That's fine for a list of tags. It's wrong for a chat history or search results.

The Set filter keeps the original order

uniqued() printed a, b, c, e, f, the first time each letter appears. seen.insert($0) returns a tuple whose inserted value is true only the first time an element is added, so filter keeps exactly the first occurrence. NSOrderedSet gave the same result, but it returns an untyped array that you have to cast, so I'd only use it in Objective-C code that already has one.

Duplicates by a property

Real data is usually structs, not letters. uniqued(by:) takes a closure that picks the key. With three contacts, removing duplicates by email kept all three, because "ana@example.com" and "ANA@example.com" are different strings. Using $0.email.lowercased() as the key kept Ana and Budi and dropped the work address. Decide what "the same" means for your data before you pick the key.

Why not check with contains?

The most common hand-written version loops over the array and appends an element only if the result doesn't contains it yet. That checks the whole result for every element, so the time grows with the square of the array size. In my run, at 40,000 random numbers, the contains loop took 0.1696 seconds and the Set filter 0.0033 seconds. At 1,000 numbers both took about 0.0001 seconds. Timings change from run to run, but the gap at large sizes doesn't: for small arrays it doesn't matter, for big ones it does.

A ready-made option

Apple's open-source Swift Algorithms package has a uniqued() method, and a uniqued(on:) version that takes a key. If your project already uses that package, use it instead of your own extension. I didn't add the package for this rewrite, so it isn't part of the run above.

A quick check for your project

  1. Search for Array(Set(. For each result, ask whether the order of that array is ever shown or compared. If it is, use the filter above.
  2. Search for loops that call contains on the array they are building. On lists that can grow into the thousands, replace them.
  3. For each place that removes duplicates from structs, write down which property makes two items "the same", and check that the code uses exactly that.

What the 2018 version said

The Gist copied the array into dataTab one element at a time, then called dataTab.removeDuplicates(), a mutating method that assigned removingDuplicates() back to the array. removingDuplicates() used addedDict.updateValue(true, forKey: $0) == nil inside filter, which is the same first-occurrence trick as seen.insert($0).inserted. It still works, so if you have it in a project there's no need to rush a change.

Sources