Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 146 ยท Collections

Arrays

Learn Swift arrays in depth - creating, indexing, appending, inserting, removing, slicing with ArraySlice, iterating, capacity, and the index-out-of-range trap and how to avoid it.

The array is the collection you will use more than any other. It stores values of one type in a fixed order, lets you reach any element by its position, and grows when you add to it. Names in a list, pixels in a row, steps in a recipe, the lines read from input: if the order matters and duplicates are fine, you want an Array.

In this lesson you will create arrays in several ways, read and change elements, add and remove in the middle, take slices, loop with and without indices, and learn what happens when you ask for an element that is not there. You met the big picture in Collections Overview; here we cover everything you do day to day with [Element].

Creating arrays

An array literal is a comma-separated list in square brackets. The element type is inferred, or you can write it in full as Array<Int> or the shorthand [Int].

Swift Ways to create an array

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.

Array(repeating:count:) is the right way to make a grid or a table of defaults. Nesting it is safe in Swift, unlike in some languages: Array(repeating: Array(repeating: 0, count: 3), count: 3) gives three independent rows, because each inner array is a value and becomes its own copy as soon as you change it.

Reading elements

Elements are numbered from zero. array[0] is the first, array[array.count - 1] the last. Because those are easy to get wrong, the standard library offers safer helpers: first, last, indices and isEmpty.

Swift Reading and checking

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.

first and last return optionals so that an empty array is not a crash. prefix, suffix, dropFirst and dropLast return slices (more on them below). They are forgiving: asking for the first ten items of a three-item array simply gives all three.

The index-out-of-range trap

A subscript with an invalid index does not return nil. It stops the program. That is a deliberate design decision: a wrong index is a bug, and continuing with garbage would hide it.

Swift Index out of range (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 run prints reading index 3 and then the process dies with SIGILL: the optimized build shows an illegal-instruction signal and a backtrace instead of a friendly message. Output printed before the crash is kept. The fixes depend on what you know:

  • Check first: if items.indices.contains(position) { ... }.
  • Use a helper that returns an optional, such as items.first, items.last, or your own safe subscript (below).
  • Restructure the loop so the index can never leave indices.
Swift A safe subscript extension

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.

Changing arrays

Everything in this section needs var. Elements can be replaced through the subscript, and the array can grow and shrink.

Swift append, insert, remove, replace

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.

Know the costs. append is amortized O(1): the array occasionally has to move to a bigger buffer, but on average each append is cheap. insert(at:) and remove(at:) are O(n) because every element after the position shifts. Removing from the front of a large array in a loop is therefore quadratic. If you need a queue, keep an index of the front item, or see the data-structure lessons later in the course.

Capacity

When an array runs out of room it allocates a bigger buffer (usually doubling) and moves the elements. If you know the final size, reserveCapacity avoids the repeated moves:

Swift Capacity and reserveCapacity

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 exact capacity numbers are an implementation detail, so test with >= and never print them in code you compare against.

Iterating

for ... in is the everyday tool. When you also need the position, use enumerated(), which yields (offset:, element:) pairs. Note that the offset starts at 0 whatever the array's indices are. For two arrays in step, zip pairs them up and stops at the shorter one.

Swift Looping over an array

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.

Do not add or remove elements while looping over the same array: the loop works on a copy (thanks to value semantics), so your changes would not affect the iteration and would only confuse you. Build a new array with filter or map, or call removeAll(where:).

Slices: ArraySlice

Subscripting with a range returns an ArraySlice<Element>, a window onto the original storage. It is cheap to make (no elements are copied), but it keeps the original indices.

Swift Slices keep their indices

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.

If you wrote middle[0] you would crash: index 0 is not in the slice, which runs from 2 to 4. Whenever you hand a slice to code that expects zero-based positions, convert with Array(slice). Also remember that a slice keeps the whole parent buffer alive; storing a tiny slice of a huge array keeps all of it in memory. The details are in Slices and Views.

Searching and testing

You do not need loops for the common questions:

Swift contains, firstIndex, min, max

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.

Methods like firstIndex(of:) need the element to be Equatable; min() and sorted() need Comparable. For your own types, adopt the protocol or pass a closure. Sorting and binary search are covered in Sorting and Searching Arrays.

Arrays of arrays, and other element types

Arrays can hold anything, including other arrays, tuples, optionals, closures and your own structs. A two-dimensional grid is an array of rows:

Swift A grid as an array of arrays

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.

An array can hold only one type. [1, "two"] fails to compile with a message about heterogeneous collection literals; if you really need mixed contents, use an enum with associated values or [Any] (a last resort, because you lose type information).

When to use an array, and when not

Use an array when the order matters, positions are meaningful, or you simply need a list to loop over. Switch to a Set for uniqueness and fast membership tests, and to a Dictionary for lookup by key. For very large queues with removal at the front, an array is the wrong shape. For fixed-size, stack-allocated data in performance-critical code, newer Swift versions offer InlineArray, which is a niche tool you can ignore for now.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does let a = [1, 2, 3]; a[3] do?

    Array subscripts do not return optionals. An invalid index is a programmer error and stops the program.
  2. 2. Which call is O(n) for a large array?

    Inserting at the front shifts every existing element one place to the right.
  3. 3. What is middle[0] if let middle = [10, 20, 30, 40][1...2]?

    ArraySlice keeps the original indices, so valid positions are 1 and 2.
  4. 4. How do you write an empty array of strings?

    An empty literal has no type information, so you must supply the element type. [:] is an empty dictionary.
  5. 5. Why does first return an optional?

    An empty array has no first element, so Swift models that as nil instead of crashing.

Summary

  • Create arrays with literals, Array(repeating:count:), map or by converting another sequence.
  • Indexes start at 0; an invalid subscript traps, while first, last and firstIndex(of:) return optionals.
  • append is amortized O(1); insert(at:) and remove(at:) are O(n).
  • enumerated() gives positions, zip pairs arrays, indices is always safe to loop over.
  • Slices (ArraySlice) share storage and keep their original indices; wrap in Array(...) for zero-based positions.
  • Arrays are value types with copy-on-write, so assigning or passing them is cheap and safe.

Next: Sorting and Searching Arrays