How can I get the nth character of a string? I tried bracket([]
) accessor with no luck.
var string = \"Hello, world!\"
var firstChar = string[
This answer is ideal because it extends String
and all of its Subsequences
(Substring
) in one extension
public extension StringProtocol {
public subscript (i: Int) -> Element {
return self[index(startIndex, offsetBy: i)]
}
public subscript (bounds: CountableClosedRange) -> SubSequence {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[start...end]
}
public subscript (bounds: CountableRange) -> SubSequence {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[start..) -> SubSequence {
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[startIndex..) -> SubSequence {
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[startIndex...end]
}
public subscript (bounds: CountablePartialRangeFrom) -> SubSequence {
let start = index(startIndex, offsetBy: bounds.lowerBound)
return self[start..
var str = "Hello, playground"
print(str[5...][...5][0])
// Prints ","