tezvyn:

Why can't you subscript a Swift String with an Int?

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

understanding Unicode-correct strings.

OUTLINE

Characters are extended grapheme clusters of variable byte width, so integer offsets are not O(1) or meaningful; String.Index is an opaque position you advance via the collection.

WHAT THIS TESTS This probes whether you understand Unicode correctness and the cost model behind Swift strings. It separates engineers who think of strings as byte arrays from those who understand grapheme clusters and why random access is not free.

A GOOD ANSWER COVERS A Swift Character is an extended grapheme cluster, a user-perceived character that may be composed of several Unicode scalars and stored as a variable number of UTF-8 bytes. The flag emoji or an accented letter formed by a base plus combining mark occupies more bytes than an ASCII letter. Because characters are not fixed width, you cannot jump to the nth character in constant time by multiplying an offset, so an integer subscript would be misleadingly slow and would invite off-by-byte bugs. Swift therefore models String as a bidirectional collection indexed by String.Index, an opaque value tied to a specific string that marks a position in storage. You get it from startIndex or endIndex and move it with index(after:), index(before:), or index(_:offsetBy:).

COMMON WRONG ANSWERS Claiming the restriction is an arbitrary API choice. Assuming one character is always one byte. Believing String.Index is just an Int wrapper that supports arithmetic like adding 5 directly.

LIKELY FOLLOW-UPS How do you get the fifth character safely? What is the difference between Character, Unicode.Scalar, and the UTF-8 and UTF-16 views? Why can an index from one string be invalid on another? What is the complexity of count?

ONE CONCRETE EXAMPLE To read the character at offset five, you write let i = str.index(str.startIndex, offsetBy: 5) then str[i]. For the string composed of a family emoji, count returns one even though its UTF-8 view holds many bytes, demonstrating why an integer subscript over bytes would not correspond to a single visible character.

Read the original → docs.swift.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.