Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 146 ยท Collections

Collections Overview

A tour of Swift's three main collections - Array, Set and Dictionary - with let and var mutability, value semantics, copy-on-write and a guide to choosing the right one.

Almost every real program keeps groups of things: the lines of a file, the users in a room, the prices in a shopping cart, the words in a sentence. Swift gives you three general-purpose collection types for this, all in the standard library and all written the same way you write a literal: Array for an ordered list, Set for a bag of unique values with no order, and Dictionary for looking up a value by a key.

This lesson is the map of the territory. You will see what each collection is good at, how let and var control whether a collection can change, why Swift collections behave like values rather than shared objects, and how copy-on-write makes that behavior cheap. The next lessons zoom into each type: Arrays, Sets and Dictionaries.

The three collections at a glance

Each collection has a literal syntax, and each one is generic: the element type is part of the type, so [Int] can only hold integers and [String: Int] maps strings to integers. Swift infers the type from the literal, so you rarely write it out.

Swift Three collections, three literals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice three things. The array keeps both 72s, because an array stores every element you give it, in order. The set silently dropped the second "swift", because a set stores each value once. And the dictionary subscript returns an optional (String?), because the key might not exist; here ?? supplies a fallback. Sets and dictionaries are unordered: the order you write a literal in is not the order you get back, and it can even change from one run of the program to the next. Whenever you print a set or dictionary, sort it first (you will see why in Dictionaries).

Choosing between them

A quick rule of thumb will serve you for most programs:

You need to... Reach for
keep things in order, allow duplicates, access by position Array
ask "is this value in the group?" quickly, keep each value once Set
look something up by a name, id or other key Dictionary

Under the hood, Set and Dictionary are hash tables. They require their elements (for a dictionary, the keys) to conform to the Hashable protocol, and in return they find an element in roughly constant time, however large the collection grows. An Array has no such requirement, but searching it for a value means looking at the elements one by one. The counting example below makes that difference visible without any timers:

Swift Why sets answer membership questions faster

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The array has to compare against every element until it finds the match (about a thousand calls). The set hashes the needle, jumps to the right bucket and compares a handful of times at most. For tiny collections the difference is invisible, and an array is often faster in practice because it is compact in memory. For thousands of lookups on thousands of items, the hash-based types win by orders of magnitude.

The nonisolated(unsafe) on the counter is there because Swift 6 rejects global mutable state that could be touched from several threads at once. It tells the compiler "trust me, only one thread uses this", which is true in this tiny program. Normally you would avoid global mutable state altogether; see the concurrency lessons later in the course.

Mutability: let versus var

Swift has no separate "mutable array" and "immutable array" types. The same Array type is either changeable or not depending on how you declare the variable. A collection stored with let can never change its contents; one stored with var can.

Swift Changing a let collection (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler refuses with an error that names the exact problem: cannot use mutating member on immutable value: 'fruits' is a 'let' constant. The fix is to declare var fruits. Prefer let by default and switch to var only when you really append, remove or reassign; the compiler will tell you if you guessed wrong, and every let collection is a promise to the reader that it never changes after the line where it is made.

Swift The same operations with var

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Constants are deep for collections of values. A let array of integers cannot change any element. But if the elements are class instances (reference types), let only freezes the array's own slots: the objects those slots point to can still be modified. You will meet that distinction again in Classes.

Value semantics

Arrays, sets and dictionaries are structs, which makes them value types. When you assign one to another variable, or pass it to a function, you get an independent copy. Changing the copy never changes the original:

Swift Copies are independent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Contrast this with languages where two variables hold the same array object, so a change through one is visible through the other. In Swift that class of bug cannot occur for these types: if a function receives an array, it cannot silently modify yours. To let a function change your array you must say so explicitly with inout (covered in Argument Labels and Parameter Names).

Copy-on-write

"Every assignment copies" sounds expensive for a million-element array. The standard library avoids the cost with copy-on-write (COW). Assigning var copy = original copies only a reference to a shared storage buffer. Both variables read from it. The real copy happens at the moment one of them mutates while the buffer is shared; from then on they own separate buffers.

You can see the mechanism with a tiny wrapper of your own. isKnownUniquelyReferenced asks whether exactly one variable owns a class instance:

Swift Building a copy-on-write wrapper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The standard library's Array, Set, Dictionary and String all work this way. The practical consequences:

  • Passing and returning collections is cheap. No elements are copied until someone mutates a shared buffer.
  • The first mutation after sharing is O(n). Appending to a copy of a large array copies the whole thing once.
  • Avoid accidental sharing in hot loops. If you keep a second reference to an array while you mutate it in a loop, the first mutation copies. Releasing the extra reference (or letting it go out of scope) before the loop avoids that.
  • Slices share too. An ArraySlice keeps the parent's buffer alive; see Slices and Views.

What the three have in common

Despite their different shapes, all three conform to the Collection family of protocols, so they share a toolbox: count, isEmpty, for ... in, map, filter, reduce, contains(where:), sorted() and many more. Learn the toolbox once and it works on all of them (the protocol details are in Collection Protocols, the transformations in map, filter, reduce and Friends).

Swift One toolbox, three collections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Empty collections are written [] for an array or set and [:] for a dictionary; because those literals carry no type information, you must give the type: var names: [String] = [] or var table = [String: Int]().

Common pitfalls

  1. Relying on order of a Set or Dictionary. It is randomized per process on purpose (to defend against hash-flooding attacks). Sort, or use an array of pairs, when order matters.
  2. Using an array where a set belongs. A loop that calls array.contains thousands of times is quadratic. Convert once with Set(array).
  3. Forgetting that lookups are optional. dictionary[key] and array.first can be nil. Handle it with if let, ?? or guard.
  4. Expecting reference behavior. Two variables holding the same array do not see each other's changes. If you need shared mutable state, wrap it in a class or an actor.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which collection should you use to store each user id at most once and test quickly whether an id is present?

    A Set stores unique, Hashable values and answers membership questions in roughly constant time.
  2. 2. What happens when you call append on an array declared with let?

    A let collection cannot be mutated. The compiler reports that you cannot use a mutating member on an immutable value.
  3. 3. After var b = a; b.append(1), where a is an array, what is true?

    Array is a struct with value semantics, so b is an independent copy as far as you can observe.
  4. 4. What does copy-on-write mean?

    Assignment shares the storage; the actual copy is deferred until one owner mutates while the buffer is shared.
  5. 5. Why should you sort a Dictionary's contents before printing them?

    Swift randomizes the hashing seed per process, so unsorted output can change from run to run.

Summary

  • Array is ordered and allows duplicates; Set is unordered and unique; Dictionary maps unique keys to values.
  • Set elements and Dictionary keys must be Hashable; lookups are roughly constant time.
  • let makes a collection immutable, var makes it mutable; prefer let unless you must change it.
  • Collections are value types: assignment and argument passing behave like independent copies.
  • Copy-on-write makes copies cheap until one owner mutates a shared buffer.
  • Never rely on set or dictionary order; sort before printing.

Next: Arrays