How can I get the nth character of a string? I tried bracket([]
) accessor with no luck.
var string = \"Hello, world!\"
var firstChar = string[
I think this is very elegant. Kudos at Paul Hudson of "Hacking with Swift" for this solution:
@available (macOS 10.15, * )
extension String {
subscript(idx: Int) -> String {
String(self[index(startIndex, offsetBy: idx)])
}
}
Then to get one character out of the String you simply do:
var string = "Hello, world!"
var firstChar = string[0] // No error, returns "H" as a String