SWIFT / CHAPTER 03

Strings and collection indices

Intermediate

Navigate text without assuming integer offsets describe characters.

By the end of this chapter

  • Use String.Index safely
  • Handle empty strings
  • Distinguish characters from encoded bytes

The idea

Swift String is a collection of Character values, each representing an extended grapheme cluster. Integer subscripts are not its character-access interface. startIndex identifies the first position, endIndex is the position after the last character, and index(after:) advances through valid positions. The first property returns an optional, naturally representing the empty-string case without a forced access.

Different views expose different units: utf8 contains encoded bytes, while the String collection contains characters. Do not substitute a byte count for a character count in a user-facing requirement. A Substring slice can share the original storage; convert it to String when you want a standalone stored value. Check boundaries before forming a range and avoid advancing past endIndex in an empty or exhausted collection.

Swift example
let text="AéB"
let second=text.index(after:text.startIndex)
print(text[second])
print(text.count)
print(text.utf8.count)
Result
é
3
4

The character view contains three characters, while UTF-8 needs two bytes for the accented letter.

Try it yourself

Return the first Character of a string or nil when empty, then convert a safe prefix to String.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which access is safe for both empty and nonempty text?