How can I get the nth character of a string? I tried bracket([]) accessor with no luck.
var string = \"Hello, world!\"
var firstChar = string[
Swift3
You can use subscript syntax to access the Character at a particular String index.
let greeting = "Guten Tag!"
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index] // a
Visit https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html
or we can do a String Extension in Swift 4
extension String {
func getCharAtIndex(_ index: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: index)]
}
}
USAGE:
let foo = "ABC123"
foo.getCharAtIndex(2) //C