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.
- Why is
Stringnot aRandomAccessCollectionofCharacter? Why isstring[i + 1]not O(1)?
A Character is an extended grapheme cluster: a user-perceived character that may be composed of many Unicode scalars — flags (two regional indicators), emoji… CharactervsUnicode.Scalarvs UTF-8 code unit?
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.
- How do you compare strings for UI versus for identifiers?
UI / search: use localized, human-facing comparison — localizedStandardCompare, localizedLowercase, formatted(), and .diacriticInsensitive search options. This…
More in Swift language
- 1.1 · Value vs reference types
- 1.2 · Optionals, pattern matching, control flow
- 1.3 · Protocols, extensions, associated types
- 1.4 · Generics, <code>some</code>, <code>any</code>
- 1.5 · Closures, escaping, capture lists
- 1.6 · Properties, observers, wrappers
- 1.7 · Access control
- 1.8 · Error handling, <code>defer</code>, ownership
- 1.10 · Codable, Sendable, macros, ABI
- 1.11 · Static vs dynamic dispatch