skip to content

Strings and Characters

A String is a collection of grapheme clusters, so indexing uses String.Index and count is linear. Interviewers ask why you cannot subscript with an Int and what a Substring keeps alive.

on this pageshow

explore

questions

5

In Swift, why can a String's count, utf8.count and unicodeScalars.count return three different numbers for the same username?

level: middleimportance: must knowfreq 65%

answer

  1. what a Character really is
  2. scalars versus code units
  3. emoji built from several scalars
  4. count walks the whole string

basics

~10 s

String.count counts Characters, and each Character is an extended grapheme cluster that may hold several Unicode scalars; unicodeScalars.count counts those scalars and utf8.count counts encoded bytes, so emoji or accents make all three differ.

solid answer

~40 s

A Swift `String` is a collection of `Character` values, and each `Character` is an **extended grapheme cluster**: one user-perceived character that may be built from several Unicode scalars. `count` has to walk the string to find those cluster boundaries, so it is O(n). `unicodeScalars.count` counts the scalars underneath, `utf8.count` counts the bytes the text occupies in UTF-8, and `utf16.count` matches `NSString.length`. So `"Zoë 👩‍👩‍👧"` is 5 characters, 9 scalars, 23 UTF-8 bytes and 12 UTF-16 units. Choose the view by what you are limiting: a character limit a person sees uses `count`; a byte budget for a database column or a network frame uses `utf8.count`.

code

swift · 11 lines
swift
let username = "Zoë 👩‍👩‍👧"
print(username.count)                // 5 Characters
print(username.unicodeScalars.count) // 9 Unicode scalars
print(username.utf8.count)           // 23 UTF-8 code units (bytes)
print(username.utf16.count)          // 12 UTF-16 code units

var word = "cafe"
word += "\u{301}"                    // COMBINING ACUTE ACCENT
print(word, word.count)              // café 4
print(word.unicodeScalars.count)     // 5
print(word.utf8.count)               // 6

go deeper

for a junior

Remember that count counts what a reader sees as characters, not bytes, and that an emoji or an accented letter can be one Character made of several scalars.

for a middle

Explain the four views, what each counts and why count is O(n), and show a concrete string where all of them differ, such as a family emoji.

for a senior

Map each product limit to the right unit: characters for user-facing limits, UTF-8 bytes for storage and wire formats, UTF-16 for Foundation ranges, and say how invalid bytes are repaired or rejected.

for a principal

Frame text limits as a contract across client, server and database; agree on one unit per boundary so a name that passes the app never overflows a column downstream.

## Four ways to measure one string A Swift `String` stores Unicode text, and Unicode text has several units of length. Swift exposes each one as its own **view**, and each view is a collection with its own `count`: | Expression | What it counts | `"Zoë 👩‍👩‍👧"` | |---|---|---| | `count` | `Character` values (extended grapheme clusters) | 5 | | `unicodeScalars.count` | Unicode scalars (code points other than surrogates) | 9 | | `utf16.count` | UTF-16 code units, the unit `NSString.length` uses | 12 | | `utf8.count` | UTF-8 code units, that is, bytes | 23 | The default view, the one you get when you iterate a `String` with `for-in` or ask for its `count`, is the `Character` view. That choice is what makes Swift strings behave like text a person reads rather than like an array of bytes. ## Why a Character is not a scalar A **Unicode scalar** is a single code point such as `U+0065` (LATIN SMALL LETTER E). An **extended grapheme cluster** is a run of one or more scalars that a reader perceives as one character. Swift's `Character` type is defined as an extended grapheme cluster, so several scalars can collapse into one `Character`: - **Combining marks.** `e` followed by `U+0301` (COMBINING ACUTE ACCENT) is one `Character`, `é`, made of two scalars. - **Zero-width-joiner sequences.** The family emoji `👩‍👩‍👧` is three person emoji glued by two `U+200D` joiners: five scalars, one `Character`. - **Modifiers.** A waving hand with a skin-tone modifier, `👋🏽`, is two scalars and one `Character`. - **Flags.** A national flag is a pair of regional-indicator scalars that render as one symbol. This has a surprising consequence that the Swift book itself demonstrates: appending a scalar does not always change `count`. Start with `"cafe"` (4 characters), append `"\u{301}"`, and the string reads `café` with a `count` of still 4, because the accent merged into the final `e`. The scalar count went from 4 to 5 and the UTF-8 count from 4 to 6. ## What each count costs Because grapheme clusters have no fixed width, the standard library cannot know how many `Character` values a string holds without looking. The doc comment on `String.count` states the cost plainly: **O(n), where n is the length of the string**. `unicodeScalars.count` also walks the string, decoding one scalar at a time. `utf8.count` is the cheap one for a native Swift string: native strings are stored as UTF-8, and the standard library returns the stored length directly; a string bridged from `NSString` goes through a slower path. Two habits follow: 1. Test emptiness with `isEmpty`, which the `count` doc comment recommends, rather than `count == 0`. 2. Do not call `count` inside a loop over a long string; compute it once, or restructure the loop around indices. ## Choosing the right count in a chat app Picture a chat app whose username field accepts emoji and accented names, and whose message preview is cut to a fixed length. Each requirement maps to a different view: - **"Usernames are at most 20 characters"** is a promise to a person, so it means `count`. Counting bytes would let `alice` have 20 letters but `Zoë 👩‍👩‍👧` only a handful. - **"The server column holds 64 bytes"** is a storage limit, so it means `utf8.count`; a name can pass a character limit and still overflow the column. - **Foundation and UIKit ranges** (`NSRange`, `NSString.length`, text-field delegate callbacks) are measured in UTF-16 units, so they agree with `utf16.count`, not with `count`. Convert between them with `Range(_:in:)` instead of mixing integer offsets. - **Truncation** must cut on a `Character` boundary, otherwise you split an emoji and display a broken glyph; that is a job for `String.Index`, covered in the material on string indices. ## Bytes that are not valid UTF-8 The views also matter in the other direction, when bytes arrive from a socket or a file. `String(decoding:as: UTF8.self)` always produces a string: it **repairs** ill-formed sequences by substituting `U+FFFD`, the replacement character, which keeps the app running but silently hides corruption. Swift 6.0 added `String(validating:as:)` (SE-0405), a failable initializer that returns `nil` instead of repairing. On Apple platforms it is available from iOS 18 and macOS 15, so code that deploys to older systems guards it with `#available`. Use repair for best-effort display and validation for anything you store, hash or compare. ## Summary - `count` answers "how many characters would a person count" and costs a walk of the string. - `unicodeScalars.count`, `utf16.count` and `utf8.count` answer encoding questions; `utf8.count` is the one a native string answers from its stored length. - The three numbers differ whenever a `Character` holds more than one scalar or a scalar needs more than one code unit, which in a modern chat app is most of the time.

  • Which Swift count matches the length Foundation's NSString reports, and why does that matter for a text-field limit?
    `utf16.count`, because `NSString.length` counts UTF-16 code units. An emoji outside the Basic Multilingual Plane takes two units and a family emoji takes several, so a limit enforced through `NSRange` offsets and one enforced with `String.count` disagree. Decide which unit the product means, usually user-visible characters, and convert ranges with `Range(_:in:)` instead of mixing integer offsets.
  • How should you turn bytes from a socket into a Swift String when they might not be valid UTF-8?
    `String(decoding:as: UTF8.self)` always succeeds and replaces ill-formed sequences with U+FFFD, which hides corruption. Swift 6.0 added `String(validating:as:)` (SE-0405), which returns `nil` instead, so you can reject or log the payload; on Apple platforms it needs iOS 18 or macOS 15 at run time. Repair for display, validate for anything you store or compare.
  • Why does the standard library recommend isEmpty over comparing String.count to zero?
    `count` is documented as O(n): it walks the whole string to find grapheme cluster boundaries just to compare the result with zero. `isEmpty` answers from the string's storage without walking it. On a long message body inside a loop or a view update, the difference is real work saved for the same answer.

  • String.count returns the number of bytes the string occupies.
  • Every Swift Character is exactly one Unicode scalar.
  • String.count is O(1) because the length is stored alongside the text.
  • utf16.count and String.count agree for anything a user can type.
  • Appending a combining accent always increases String.count by one.

Assumes Swift 6.4; the counting rules hold in every supported release, while String(validating:as:) arrived in Swift 6.0 (SE-0405) and needs iOS 18 or macOS 15 at run time.

open as a page

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%

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.

open as a page

In Swift, how do multiline string literals and raw strings with # delimiters change escaping, indentation and interpolation?

level: juniorimportance: should knowfreq 40%

basics

~20 s

A triple-quoted multiline literal keeps line breaks and strips the indentation of its closing delimiter. Wrapping a literal in # signs makes backslashes and quotes literal; escapes and interpolation then need the same number of #, as in #(name).

open as a page

In Swift, why does slicing a String give you a Substring, and when should you convert it back with String(_:)?

level: middleimportance: should knowfreq 55%

basics

~20 s

Slicing a String returns a Substring that shares the original's storage, so slicing is cheap. Because it keeps that whole storage alive, convert with String(_:) before storing it or passing it to an API that takes String.

open as a page

In a Swift chat app, why does == report two usernames equal when their UTF-8 bytes differ, and where does that bite?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Swift's String and Character == compare by Unicode canonical equivalence, so precomposed ë and e plus a combining diaeresis are equal though their bytes differ. Sets agree, but a server or hash that compares bytes does not.

open as a page