Photo by Alfons Morales on Unsplash

Why cannot subscript String with an Int in Swift

Banghua Zhao
2 min readOct 20, 2020

--

In Swift, String cannot be subscripted by an Int. For example, the following code will get an error:

let name = "Neil"
name[2]
// 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.

Why is that? The short answer is that Swift considers String as a collection of grapheme clusters and grapheme clusters do not have a fixed size and cannot be indexed like an array (grapheme clusters are represented by the Swift type Character).

To understand that, we first need to know what is grapheme clusters. According to Apple’s documentation:

An extended grapheme cluster is a sequence of one or more Unicode scalars that (when combined) produce a single human-readable character.

This means a character (a grapheme cluster) in Swift can be presented by either one Unicode scalar or multiple Unicode scalars. For example:

let letterNorml = “é”let letterCombining = “e\u{0301}”for code in letterNorml.unicodeScalars {print(code.value)}// 233for code in letterCombining.unicodeScalars {print(code.value)

--

--