Access Swift String by Index
Last Run on XCODE 11.4 / Swift 5.2
The swift string class does not provide the ability to get a character at a specific index because of its native support for UTF characters.
In the code snippets below, we will walk through code to access elements of a string at speific positions.
Getting the first Character
let mySwiftString = "Swift is awesome!"
//Getting the first Character
mySwiftString.first
let firstIndex = mySwiftString.startIndex
mySwiftString[firstIndex]
Getting the last Character
let mySwiftString = "Swift is awesome!"
//Getting the last Character
mySwiftString.last
let lastIndex = mySwiftString.index(before: mySwiftString.endIndex)
mySwiftString[lastIndex]
Getting the 2nd Character
let mySwiftString = "Swift is awesome!"
//Getting the 2nd Character
let secondIndex_Ver1 = mySwiftString.index(after: firstIndex)
mySwiftString[secondIndex_Ver1]
let secondIndex_Ver2 = mySwiftString.index(firstIndex, offsetBy: 1)
mySwiftString[secondIndex_Ver2]
Getting the Nth Character from start ( Say 3rd)
let mySwiftString = "Swift is awesome!"
//Getting the Nth Character from start ( Say 3rd )
let thirdIndex = mySwiftString.index(firstIndex, offsetBy: 2)
mySwiftString[thirdIndex]
Getting the Nth Character from end ( Say 3rd last )
let mySwiftString = "Swift is awesome!"
//Getting the Nth Character from end ( Say 3rd last )
let thirdLastIndex = mySwiftString.index(lastIndex, offsetBy: -2)
mySwiftString[thirdLastIndex]