#39: String Characters by Index in Swift

Swift strings are Unicode-correct, so you cannot index them with plain integers.

Use String.Index instead:

let text = "Swift"
let index = text.index(text.startIndex, offsetBy: 2)
let character = text[index]
// "i"

That may look more verbose than text[2], but it keeps string operations correct even when characters are composed of multiple Unicode scalars.

If you need this often, wrap it in a small helper rather than repeatedly converting indexes inline.


I'm also on Twitter and GitHub.

Subscribe via RSS.