skip to content

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%

answer

  1. same meaning and appearance
  2. precomposed versus combining
  3. hashing follows equality
  4. the server may compare bytes

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.

solid answer

~40 s

Two `String` or `Character` values are equal in Swift when their extended grapheme clusters are **canonically equivalent**: same linguistic meaning and appearance, even if built from different scalars. `"Zo\u{EB}"` and `"Zo\u{65}\u{308}"` are `==`, have the same `count`, and hash alike, so a `Set<String>` treats them as one username. Their `utf8` views still differ (4 bytes vs 5), and Swift does not normalize what it stores. That bites at boundaries: a backend or database comparing bytes sees two different names, a digest over `utf8` differs, and `hasPrefix("Zoe")` is false on the decomposed form because its last `Character` is `ë`. Canonical equivalence also does not catch look-alikes: Latin `A` and Cyrillic `А` are unequal.

code

swift · 15 lines
swift
let precomposed = "Zo\u{EB}"          // ë as one scalar, U+00EB
let decomposed  = "Zo\u{65}\u{308}"   // e + COMBINING DIAERESIS

print(precomposed == decomposed)                       // true
print(precomposed.count, decomposed.count)             // 3 3
print(precomposed.utf8.count, decomposed.utf8.count)   // 4 5
print(precomposed.utf8.elementsEqual(decomposed.utf8)) // false

let taken: Set<String> = [precomposed]
print(taken.contains(decomposed))                      // true

print(decomposed.hasPrefix("Zoe"))                     // false: last Character is ë

let latinA: Character = "\u{41}", cyrillicA: Character = "\u{410}"
print(latinA == cyrillicA)                             // false

go deeper

for a junior

Remember that Swift compares strings by what they mean and look like, so é typed two different ways is still equal with ==.

for a middle

Explain precomposed versus decomposed scalars, why count and == agree while utf8 differs, and that hashing is consistent with ==.

for a senior

Trace where a byte-comparing server, a digest or a prefix check disagrees with ==, and propose normalization at the boundary with tests for both spellings.

for a principal

Own the identifier policy across client and server: one normalization form, explicit case rules and a confusables check, so equality means the same thing everywhere.

## What Swift's == compares Unicode often offers more than one way to spell the same character. `ë` can be the single scalar `U+00EB` (LATIN SMALL LETTER E WITH DIAERESIS), called **precomposed**, or `e` followed by `U+0308` (COMBINING DIAERESIS), called **decomposed**. Unicode defines these two spellings as **canonically equivalent**: they have the same meaning and render identically. Swift's `String` and `Character` equality is defined in those terms. The Swift book states that two `String` values, or two `Character` values, are equal if their extended grapheme clusters are canonically equivalent. So, in the code example: - `precomposed == decomposed` is `true`. - Both have a `count` of 3, because `ë` is one `Character` either way. - Their UTF-8 views differ: 4 bytes against 5, and `utf8.elementsEqual(_:)` returns `false`. The stored bytes are not normalized. Swift compares as if both sides were normalized, but it keeps whatever scalars you gave it. ## Hashing follows equality `String` conforms to `Hashable`, and hashing must agree with `==`: equal values hash alike. Swift honours that for canonically equivalent strings, so a `Set<String>` holding the precomposed name reports `contains(decomposed)` as `true`, and a `Dictionary` keyed by one spelling finds the other. Inside a Swift process, the two spellings behave as one value. ## Where it bites The trouble starts where text leaves Swift's notion of equality. In a chat app with accented and emoji-heavy usernames, typical places are: - **The server.** One client sends `Zoë` precomposed, another device sends it decomposed. The app's `Set` says the name is taken; a backend that compares raw bytes says it is free. Two accounts end up with names that look and compare identical in the app. - **Digests and signatures.** A hash, HMAC or signature computed over `utf8` differs between the two spellings, even though `==` says the strings match. - **Prefix and suffix checks.** `hasPrefix(_:)` and `hasSuffix(_:)` compare **Character by Character** with canonical equivalence, as the book notes. On `"Zo\u{65}\u{308}"`, `hasPrefix("Zoe")` is `false`, because the third `Character` is `ë`, not `e`. A byte-level or scalar-level prefix check would say `true`. - **Scalar-level comparisons.** Comparing `unicodeScalars` views, or bridging through APIs that compare UTF-16 units literally, can give a different answer from `==`. ## What == does not do Canonical equivalence is narrow, and a few assumptions about it are wrong: | Assumption | Reality in Swift | |---|---| | `==` ignores case | No; `"zoë" == "Zoë"` is `false` | | `==` catches look-alike letters | No; Latin `A` (`U+0041`) and Cyrillic `А` (`U+0410`) are unequal | | `==` compares bytes | No; precomposed and decomposed spellings are equal | | Equal strings have equal `utf8.count` | No; the two `ë` spellings differ by one byte | Look-alike characters from different scripts are a security concern for usernames, and solving them takes a confusables policy, which is beyond what `==` offers. The same canonical-equivalence rule applies to `Character`: `Character("\u{EB}") == Character("e\u{308}")` is `true`, because a `Character` is one extended grapheme cluster and its equality is defined the same way as `String`'s. That is why a loop that compares a username Character by Character with another reaches the same verdict as `==` on the whole string, while a loop over `unicodeScalars` or `utf8` does not; the view you iterate decides which notion of sameness you get. ## Making boundaries agree The fix is to choose one representation wherever text crosses a boundary that compares bytes: 1. **Normalize at the boundary.** Convert usernames to one Unicode normalization form before sending, storing or hashing them, and have the server enforce the same form; Foundation offers normalization APIs for this. 2. **Compare the view that matches the contract.** When a protocol is defined over bytes, compare `utf8` views explicitly, so the code says what it means. 3. **Decide case and look-alike policy separately.** Case-insensitive matching and confusable detection are separate product rules, not properties of `==`. 4. **Test with both spellings.** Unit tests that type names on a keyboard usually produce precomposed text; add decomposed fixtures written with `\u{…}` escapes. ## Summary Swift's `==` answers "would a reader consider these the same text", and `Hashable` agrees with it. Bytes, digests, servers and prefix checks on decomposed text may disagree, so the app must normalize or compare explicitly wherever those meet.

  • Why does "Zo\u{65}\u{308}".hasPrefix("Zoe") return false in Swift?
    `hasPrefix(_:)` compares Character by Character using canonical equivalence. In the decomposed string, `e` and the combining diaeresis form one extended grapheme cluster, `ë`, so the third Character is `ë` and does not match `e`. A comparison over `unicodeScalars` or `utf8` would see a matching prefix, which is exactly why mixing views gives inconsistent answers.
  • Does Swift's String == treat Latin A and Cyrillic А as equal?
    No. Canonical equivalence covers different encodings of the same character, not characters from different scripts that merely look alike. Latin `U+0041` and Cyrillic `U+0410` have different meanings, so `==` returns false. Preventing look-alike usernames needs a separate confusables policy enforced by the app and the server.
  • How do you keep a Swift client and a byte-comparing server in agreement about usernames?
    Pick one Unicode normalization form, apply it on the client before sending or hashing, and enforce the same form on the server so stored names are canonical. Then byte comparison and Swift's `==` agree. Test with both precomposed and decomposed fixtures, because keyboard input in tests is usually precomposed and hides the problem.

  • Swift's String == compares the underlying UTF-8 bytes.
  • Two strings that are == always have the same utf8.count.
  • Swift normalizes every string to one form when it is stored.
  • == also ignores case and look-alike letters from other scripts.
  • A Set<String> can hold both spellings of the same accented name.