LESSON 3 OF 6

Collections and transformations

Choose arrays, sets, and dictionaries for the right job.

Choose a collection

An Array preserves order and can contain duplicates. A Set stores unique Hashable values without a defined order. A Dictionary associates unique keys with values. Model the behavior you need rather than choosing by habit.

Transform without mutation

map transforms every value; filter keeps values that satisfy a predicate; compactMap drops nil transformations. Each returns a new result, which often makes a pipeline easier to reason about.

Preserve useful order

Deduplicating by converting an array to a set loses its order. The example below combines Set membership with filter to keep the first occurrence in its original position.

Try it yourself

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

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

Continue with the official Swift language guide