Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 146 ยท Collections

Slices and Views

Learn Swift slices and views - ArraySlice, Substring and Slice, preserved indices, copy-on-write, memory retention, String views, Dictionary Keys and Values, and how to avoid slicing mistakes.

Taking part of a collection is one of the most common things programs do: the first three results, everything after the header line, the word between two spaces. A beginner would expect the answer to be a new, smaller array or string. In Swift it usually is not. array[1...3] and text.prefix(5) return a slice: a lightweight view that points into the original collection's storage and remembers which part is "its" part. Creating it is instant and copies nothing.

That design is efficient, and it comes with three surprises that catch almost everyone once: slice indices do not start at zero, a slice keeps its whole parent alive in memory, and a Substring is a different type from String. This lesson explains how slices work, shows each surprise failing, and ends with the other "views" that the standard library gives you (reversed(), Dictionary.Keys, and the Unicode views of a string).

Slices are views, not copies

Any Collection can be sliced with a range, and the result type is the collection's associated type SubSequence. For the common types:

Swift What slicing returns

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 slices are ArraySlice<Element>, String slices are Substring, and a range of integers slices into another Range. Types without a special slice, including your own collections, get the generic wrapper Slice<Base>, which you met in Collection Protocols. prefix, suffix, dropFirst, dropLast, prefix(while:), split and subscripting with a range all return slices.

All of the slice types are themselves collections, so everything from Arrays and Strings works on them: map, filter, count, first, sorted(), joined(), for-in.

Indices keep their original numbers

This is the single most important fact about slices. A slice shares the indices of the collection it was cut from. If you slice elements 2 through 4 out of an array, the slice's first index is 2, not 0:

Swift Slice 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.

It looks odd, but it has a purpose: an index you obtained from the parent still means the same position in the slice. That lets you cut a collection down, search it, and report the answer in terms of the original positions without any arithmetic.

It also sets a trap. Code that reaches for slice[0] assumes zero-based positions, and that is only true for arrays that are not slices:

Swift slice[0] is not the first element (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.

tail.first is 30 and tail[2] is also 30, but tail[0] asks for an index before the slice's start, so the program traps (Illegal instruction, signal 4, with a backtrace). Slicing does not warn you at compile time. Better habits:

  • Use first, last, startIndex and indices instead of literal numbers: tail[tail.startIndex].
  • Use dropFirst() / prefix(1) / first for "the head and the rest" and never index 0 or count - 1 on a collection that might be a slice. For the last element use last, or index(before: endIndex); count - 1 is only right when startIndex is 0.
  • Convert with Array(slice) when you want an ordinary zero-based array (and are happy to pay for a copy).

When a function receives a generic Collection, never assume its indices start at 0. Use startIndex and the collection's index(_:offsetBy:), which work for slices, strings and everything else.

Copy-on-write: slices are independent when you change them

Since a slice points into its parent's storage, you might fear that changing one changes the other. It does not. Arrays and their slices have value semantics (see Collections Overview); the storage is shared only while nobody modifies it, and the first write makes a private copy.

Swift Mutating a slice does not touch the original

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.

After middle[2] = 99, the slice has its own copy of those three elements and original is unchanged. Later changes to original do not leak into middle either. Notice that the slice still uses the parent's numbering (index 2), and that it can grow with append.

One variation does write through to the parent, because it is not a stored slice but a temporary one: modifying through the range subscript itself.

Swift Modifying a range in place

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[range] has a getter and a setter, so calling a mutating method on it edits the parent in place. Compare this with var middle = original[1...3], where you stored the slice and from then on edit a separate value. Both are useful: the first is how you sort part of an array without extra memory.

The memory trap: slices keep their parent alive

A slice holds a reference to the parent's whole storage. If you read a 500 MB file into one String, cut out a 10-byte Substring and keep only that, the 500 MB stays allocated for as long as the substring lives.

Swift
// Read-only example: the idea, with made-up sizes
func extractTitle(from document: String) -> Substring {
    document.prefix(40)           // tiny view, but it keeps all of `document` alive
}

func extractTitleSafely(from document: String) -> String {
    String(document.prefix(40))   // copies 40 characters; the document can be freed
}

The rule from the Swift standard library designers is simple:

  • Short-term, local use (parsing, searching, passing to a helper): keep the slice. It is free.
  • Long-term storage (properties, caches, results returned to callers, anything that outlives the parent): convert with String(...) or Array(...).

That is why Substring is a distinct type. If it could pass as a String everywhere, it would be too easy to keep a huge parent alive by accident. The type system forces you to write the conversion at the boundary.

Substring in practice

Swift Substring and its parent

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.

A Substring lets you use the parent's index, so line[eq] is legal and tells you the position of the equals sign in the full line. You can think of a Substring as "a string plus a window".

Substring is not String (and what to do about it)

Because they are different types, passing one where the other is expected fails:

Swift Substring where String is expected (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 error reads cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'. There are two good solutions. Convert at the call site, or accept both types by writing the function against the StringProtocol that String and Substring share:

Swift Two fixes

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.

map(String.init) is the idiomatic way to turn every substring into a real string at once.

Slicing algorithms: head and tail

Slices make recursive algorithms read naturally, because "the rest of the list" costs O(1) to create:

Swift Recursion with ArraySlice

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.

Look at the last loop: the chunks print with starting indices 0, 3 and 6, which is the index-preservation rule at work. In the binary search, the code uses sorted.startIndex and sorted.index(_:offsetBy:), never a bare 0, and it works for every recursive level.

Each dropFirst() in sum is O(1), but the function is still recursive and uses stack space proportional to the length; for long inputs prefer a loop or reduce. Recursion discusses stack depth.

Views you already use

A view is a collection that presents another collection's data in a different way, without copying it. Slices are one kind. The standard library has several others:

Swift Other views

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.

zip(numbers, numbers.dropFirst()) is a classic idiom: pair every element with its neighbour, with no copying. Here it computes the differences between consecutive numbers. Dictionary.Values is a mutable collection, so you can change every value without looking keys up again.

The Unicode views of a String

A string can be viewed as characters, Unicode scalars, UTF-8 bytes or UTF-16 code units. Each view is a collection over the same storage:

Swift Four ways to look at one string

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.

count on a String counts characters (what a reader sees as one symbol), so it needs to scan the string, O(n). utf8.count is O(1) for native strings, which is why code that only needs the byte size, for example a size limit on a network field, should use it. The view's index type is the same as String's, so an index found in the UTF-8 view can slice the string, as the last example does. When you care about visible symbols, stay at the Character level; when you speak to a file format or a protocol, use utf8.

Ranges as values

A range such as 2..<5 is also a small value you can store, pass and compute with. You can use it to cut several collections consistently:

Swift Ranges used for slicing

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.

names[tooBig] would trap because 20 is out of bounds; clamped(to:) first trims the range to the valid indices. Ranges covers the range types in full.

Practical guidelines

  • Slicing is O(1); copying out is O(n). Pass slices between helper functions freely, and copy with Array(...) or String(...) at boundaries.
  • Never hard-code 0 or count - 1 for a collection that may be a slice. Use startIndex, endIndex, first, last and indices.
  • Do not store a slice long-term unless you want its parent to stay alive.
  • A mutating call on array[range] edits the array. Storing the slice in a variable creates an independent value instead.
  • Accept the most general parameter type that makes sense: StringProtocol for text, some Collection<Int> or ArraySlice for sequences of numbers, so callers do not need to convert.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of [1, 2, 3, 4][1...2]?

    Slicing an Array gives an ArraySlice, a view into the array's storage that shares the original indices.
  2. 2. Given let tail = [10, 20, 30, 40][2...], what does tail[2] return?

    The slice keeps the parent's indices, so index 2 is the slice's first element, 30. tail[0] would trap because it is before the slice's startIndex.
  3. 3. Why do Swift APIs usually want you to convert a Substring to a String before storing it?

    The substring is a window into the parent's storage. Keeping it keeps the whole parent allocated; String(substring) copies just the part you need.
  4. 4. What does var scores = [3, 1, 2, 0]; scores[0...2].sort() do?

    The range subscript has a setter, so a mutating call on it writes back into the array. scores becomes [1, 2, 3, 0].
  5. 5. Which generic constraint lets one function accept both String and Substring?

    String and Substring both conform to StringProtocol, so a function generic over it accepts either without conversion.

Summary

  • Slicing (a[1...3], prefix, dropFirst, split) returns a view: ArraySlice, Substring or Slice<Base>, created in O(1) without copying.
  • Slices keep the parent's indices, so use startIndex, first and indices instead of 0; slice[0] can trap.
  • A stored slice becomes independent on its first write (copy-on-write), but array[range].sort() edits the array in place.
  • A slice keeps its parent's storage alive: copy with Array(...) or String(...) before storing long-term.
  • Substring is not String; convert with String(_:) or write generic code over StringProtocol.
  • Other views include reversed(), zip, enumerated(), Dictionary.Keys and Values, and the unicodeScalars, utf8 and utf16 views of a string.

Next: Collection Algorithms by Hand