1.9 · Strings and Unicode

A Swift String is a sequence of grapheme clusters, not characters or bytes. Every surprising count, index, and comparison behaviour follows from that.

Mental model. Three layers: bytes (UTF-8) → scalars (code points) → Characters (what a human sees). Swift’s default view is the top layer, and it is the most expensive to index.

What a character is

Graphemes, scalars and bytes.

  1. Why is String not a RandomAccessCollection of Character? Why is string[i + 1] not O(1)? 1.9.1 · L1
    A Character is an extended grapheme cluster: a user-perceived character that may be composed of many Unicode scalars — flags (two regional indicators), emoji…
  2. Character vs Unicode.Scalar vs UTF-8 code unit? 1.9.2 · L2
    Unicode scalar — one code point (roughly, one “letter” in the Unicode table). Character — a grapheme cluster: one or more scalars that a human reads as one…

Comparing strings

Equality means different things for UI and IDs.

  1. How do you compare strings for UI versus for identifiers? 1.9.3 · L3
    UI / search: use localized, human-facing comparison — localizedStandardCompare, localizedLowercase, formatted(), and .diacriticInsensitive search options. This…

More in Swift language