skip to content

In Swift, why can't you subscript a String with an Int, and what does index(_:offsetBy:) cost when you truncate a message preview?

level: seniorimportance: must knowfreq 60%

answer

  1. variable-width Characters
  2. no constant-time jump to position n
  3. an opaque position, not an offset
  4. limitedBy instead of a trap

basics

~20 s

Characters in a Swift String have variable width, so reaching the nth one means walking from an end. Swift marks the Int subscript unavailable instead of hiding that cost, and index(_:offsetBy:) is O(n) in the distance it moves.

solid answer

~40 s

A `String` is a `BidirectionalCollection`, not a `RandomAccessCollection`: its `Character` values are grapheme clusters of different byte lengths, so finding the nth one requires walking. The standard library declares an `Int` subscript only to mark it unavailable, and the compiler says "cannot subscript String with an Int, use a String.Index instead." You build a `String.Index` from `startIndex` or `endIndex` with `index(_:offsetBy:)`, which is documented as O(n) where n is the distance, and traps with "String index is out of bounds" if it runs past the end. For a preview, use `index(_:offsetBy:limitedBy:)` or `prefix(_:)`, cut once, and never call `index(_:offsetBy:)` inside a loop over every position: that turns a linear scan quadratic.

code

swift · 13 lines
swift
func messagePreview(_ text: String, maxCharacters: Int) -> String {
    guard let cut = text.index(text.startIndex,
                               offsetBy: maxCharacters,
                               limitedBy: text.endIndex),
          cut < text.endIndex else {
        return text                      // already short enough
    }
    return String(text[..<cut]) + "…"
}

let body = "Привет 👋🏽 see you at the café tonight"
print(messagePreview(body, maxCharacters: 8))   // Привет 👋🏽…
print(messagePreview("ok 👍", maxCharacters: 4))  // ok 👍

go deeper

for a junior

Recall that text[3] does not compile in Swift and that you step from startIndex with index(_:offsetBy:), remembering endIndex is one past the last character.

for a middle

Explain variable-width grapheme clusters, why String is bidirectional but not random-access, and quote the O(n) cost of index(_:offsetBy:) from its documentation.

for a senior

Spot the quadratic loop, the foreign index and the index kept across a mutation in review, and write a truncation that never traps or splits an emoji.

for a principal

Treat integer-offset helpers on String as a smell to settle in code review; a convenience extension that hides the walk spreads quadratic loops through a codebase.

## Why there is no Int subscript In many languages `text[3]` is a constant-time jump, because every character has the same width. In Swift, a `Character` is an **extended grapheme cluster**: `a` is one byte of UTF-8, `é` is two, and a family emoji is eighteen. There is no arithmetic that turns "the fourth character" into a memory position; the only way to find it is to walk from the start (or the end) and detect cluster boundaries as you go. Swift could have hidden that walk behind a familiar `text[3]` subscript, but then code that looks constant-time would be linear, and a loop over every position would be quadratic without any sign in the source. Instead the standard library declares the `Int` subscript and marks it unavailable, so the attempt fails at compile time: ```plaintext error: 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead. ``` In type terms, `String` conforms to `BidirectionalCollection` (you can step forward and backward) but not to `RandomAccessCollection` (you cannot jump). ## What String.Index really is A **`String.Index`** is an opaque position inside one particular string. Under the hood it records an offset in the string's code units plus a few flags, such as whether the position is known to sit on a `Character` boundary. You never construct one from an integer directly; you derive it: - `startIndex` is the first `Character`; `endIndex` is **one past the last**, so `text[text.endIndex]` traps. - `index(after:)` and `index(before:)` step one `Character`. - `index(_:offsetBy:)` steps n `Character` values, and `index(_:offsetBy:limitedBy:)` returns `nil` instead of overshooting. - Searching methods such as `firstIndex(of:)` return an index directly. Because the index is an offset into one string's storage, it is only meaningful for that string, or for a `Substring` sliced from it, which shares the same index space. ## The cost model The complexities below are quoted from the doc comments in the standard library source: | API | Documented cost | |---|---| | `String.count` | O(n), n is the length of the string | | `index(_:offsetBy:)` | O(n), n is the absolute value of the distance | | `index(_:offsetBy:limitedBy:)` | O(n), n is the absolute value of the distance | | `prefix(_:)` on a `String` | O(k), k is the number of elements selected | | `String(_:)` from a `Substring` | O(n), n is the length of the substring | The trap is not any single call; it is repetition. `for i in 0..<text.count { text[text.index(text.startIndex, offsetBy: i)] }` walks from the start on every iteration, so the loop does about n²/2 steps. Iterating the string directly (`for ch in text`), using `indices`, or carrying an index forward with `index(after:)` keeps the whole pass linear. ## Truncating a preview safely Take a chat list that shows the first N characters of each message followed by an ellipsis. A correct implementation: 1. Ask for the cut point with `index(_:offsetBy:limitedBy:)`, passing `endIndex` as the limit, so a short message yields `nil` instead of a trap. 2. If the cut point is `nil` or equals `endIndex`, the message already fits; return it unchanged. 3. Slice with `text[..<cut]`, which yields a `Substring` and cuts on a `Character` boundary, so an emoji with a skin-tone modifier is never split. 4. Convert with `String(_:)` before appending the ellipsis and storing the result. `text.prefix(n)` does the same walk in one call and never traps when n exceeds the length; it is the shorter choice when you do not need the index itself. ## Index misuse that compiles Indices are typed, but the type does not say which string an index belongs to, so some mistakes compile and fail only at run time: - **An index from another string.** Swift checks that an index is in bounds, not where it came from. A foreign index either traps with "String index is out of bounds" or silently reads whatever sits at that code-unit offset, which can be a different character or a mangled one. - **`endIndex` as a subscript.** It is a valid index for ranges and comparisons, never for reading a `Character`. - **Indices kept across a mutation.** The doc comments on `insert(_:at:)`, `remove(at:)`, `replaceSubrange(_:with:)` and `removeSubrange(_:)` all state that calling them **invalidates any existing indices** for that string. The safe pattern is to derive an index from the string you are about to read, use it immediately, and recompute after any mutation.

  • Why is a loop that calls index(_:offsetBy:) with the loop counter on every iteration a performance bug in Swift?
    Each call walks from `startIndex` to position i, and `index(_:offsetBy:)` is documented as O(n) in the distance, so a loop over n positions costs about n²/2 steps. On a long message body that is visible in a profile. Iterate the string directly, use `indices`, or carry an index forward with `index(after:)` so the pass stays linear.
  • What happens in Swift if you use a String.Index computed on one string to subscript a different string?
    Nothing checks where the index came from. If its offset is beyond the other string, the subscript traps with "String index is out of bounds"; otherwise it reads whatever sits at that code-unit offset, which can be a different or garbled character. Derive indices from the string you read, or from a `Substring` of it, which shares its index space.
  • When is prefix(_:) a better choice than index(_:offsetBy:limitedBy:) for a Swift message preview?
    When you only need the leading characters, not the position. `prefix(_:)` walks at most k characters, returns a `Substring` cut on a `Character` boundary, and simply returns the whole string when k exceeds its length, so there is no optional to unwrap and no trap to guard against. Use the index form when you need the cut position for something else, such as styling.

  • String lacks an Int subscript by oversight; it would be as fast as Array's.
  • index(_:offsetBy:) is O(1) because String.Index is an integer offset.
  • A String.Index from one string is safe to use on any other string.
  • text[text.endIndex] reads the last character of the string.
  • Indices stay valid after insert(_:at:) or remove(at:) on the same string.