Grammarly: String Index Type Safety in Swift
Original post String Index Type Safety in Swift
Article Summary
Victor Pavlychko from Grammarly reveals how a single emoji nearly broke their iOS keyboard. The culprit? Treating all string indices as equals when they're fundamentally different.
Grammarly's iOS team discovered critical bugs in their text manipulation logic caused by mixing incompatible string index types. Swift's default string indexing (grapheme clusters) clashed with Apple's UTF-16 based APIs, causing text edits to fail unpredictably. Their solution leverages Swift's type system to prevent these encoding mismatches at compile time.
Key Takeaways
- One emoji (๐ฉ๐ผโ๐ซ) uses 7 UTF-16 code units but counts as 1 grapheme cluster
- Apple's deleteBackward uses grapheme indices while adjustTextPosition uses UTF-16 offsets
- Created IndexOffset generic wrapper to make string index types incompatible
- Type system now prevents using wrong index type at compile time
By wrapping string indices in strongly typed generics, Grammarly eliminated an entire class of text manipulation bugs that stemmed from mixing UTF-16 and grapheme cluster counting.
Continue reading
This page summarizes “String Index Type Safety in Swift” by Grammarly, published Mar 7, 2022. All credit for the original work goes to the authors.