String Index Type Safety in Swift
Article Summary
Grammarly's iOS team discovered their text editing bugs weren't logic errors. They were using the wrong kind of integer.
When building their iOS keyboard, Grammarly engineers found that Swift's string indexing was causing subtle but serious bugs. The culprit? Apple's APIs use different definitions of 'character' without type safety to prevent mixing them up.
Key Takeaways
- Swift counts grapheme clusters (👩🏼🏫 = 1), but UTF-16 uses code units (same emoji = 7)
- Apple's deleteBackward and adjustTextPosition use incompatible index types
- Generic phantom types enforce index safety without runtime overhead
- Type system now prevents using grapheme indices where UTF-16 expected
Critical Insight
Wrapping string indices in generic types turned runtime text manipulation bugs into compile-time errors.