How can I get the nth character of a string? I tried bracket([]
) accessor with no luck.
var string = \"Hello, world!\"
var firstChar = string[
Swift 2.0 as of Xcode 7 GM Seed
var text = "Hello, world!"
let firstChar = text[text.startIndex.advancedBy(0)] // "H"
For the nth character, replace 0 with n-1.
Edit: Swift 3.0
text[text.index(text.startIndex, offsetBy: 0)]
n.b. there are simpler ways of grabbing certain characters in the string
e.g. let firstChar = text.characters.first