When you want to get a character at n-th index from a string, you usually try to do it something like this:
let string = "pikachu" let character = string // expect "a".
However, it doesn’t work. It’s because Swift
String type has its
String.Index type, and it is different from other
String.Index is declared as
typealias Index = String.CharacterView.Index. On the other hand,
Array.Index is declared as
typealias Index = Int. Both of them are named Index, but under the hood of typealias, they are different types.
let string = "pikachu" let index = string.index(string.startIndex, offsetBy: 3) // 4th index is retrieved.
Now you get an index of type
String.Index. You can use it for subscript.
let character = string[index] print(character) // -> "a" is printed out.
Now you can print out a character from a string using index ⚡️