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 4
String(Array(stringToIndex)[index])
This is probably the best way of solving this problem one-time. You probably want to cast the String as an array first, and then cast the result as a String again. Otherwise, a Character will be returned instead of a String.
Example String(Array("HelloThere")[1])
will return "e" as a String.
(Array("HelloThere")[1]
will return "e" as a Character.
Swift does not allow Strings to be indexed like arrays, but this gets the job done, brute-force style.