Swift String Index takes grapheme clusters into account. It means it respects the presence of Unicode characters in your String.
ā get first character from šØāš©āš¦ == šØāš©āš¦ ā get second character from šØāš©āš¦ == index out of bounds
In Javascript, you get the unicode character.
"šØāš©āš¦"[0] == '\uD83D'
Get character at Int
index
let intIndex = 3 let input = "This is emoji family šØāš©āš¦" let index = input.index(input.startIndex, offsetBy: intIndex) let char = input[index] print(char) // prints "s"
Convert Int
to String.Index
input.index(input.startIndex, offsetBy: 3)
The above code will convert
3
to the corresponding String.Index
of input
.Negative offset from .endIndex
let intIndex = -3 let input = "This is emoji family" let index = input.index(input.lastIndex, offsetBy: intIndex) let char = input[index] print(char) // prints "i"
Ā