How can I get the nth character of a string? I tried bracket([]
) accessor with no luck.
var string = \"Hello, world!\"
var firstChar = string[
Here's an extension you can use, working with Swift 3.1. A single index will return a Character
, which seems intuitive when indexing a String
, and a Range
will return a String
.
extension String {
subscript (i: Int) -> Character {
return Array(self.characters)[i]
}
subscript (r: CountableClosedRange) -> String {
return String(Array(self.characters)[r])
}
subscript (r: CountableRange) -> String {
return self[r.lowerBound...r.upperBound-1]
}
}
Some examples of the extension in action:
let string = "Hello"
let c1 = string[1] // Character "e"
let c2 = string[-1] // fatal error: Index out of range
let r1 = string[1..<4] // String "ell"
let r2 = string[1...4] // String "ello"
let r3 = string[1...5] // fatal error: Array index is out of range
n.b. You could add an additional method to the above extension to return a String
with a single character if wanted:
subscript (i: Int) -> String {
return String(self[i])
}
Note that then you would have to explicitly specify the type you wanted when indexing the string:
let c: Character = string[3] // Character "l"
let s: String = string[0] // String "H"