Collections ยท SWIFT RECIPE

Remove duplicates from an array

Keep the first occurrence in the original order.

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

How it works

Set.insert reports whether insertion was new. filter keeps only new values, preserving their input order. Converting a Set back to an Array does not preserve that order.

EXPECTED OUTPUT
[3, 1, 2]

Keep in mind

Elements must be Hashable. For custom records, deduplicate by a stable identifier.

Read the Swift language reference