How can I get the nth character of a string? I tried bracket([]
) accessor with no luck.
var string = \"Hello, world!\"
var firstChar = string[
Xcode 11 • Swift 5.1
You can extend StringProtocol to make the subscript available also to the substrings:
extension StringProtocol {
subscript(_ offset: Int) -> Element { self[index(startIndex, offsetBy: offset)] }
subscript(_ range: Range) -> SubSequence { prefix(range.lowerBound+range.count).suffix(range.count) }
subscript(_ range: ClosedRange) -> SubSequence { prefix(range.lowerBound+range.count).suffix(range.count) }
subscript(_ range: PartialRangeThrough) -> SubSequence { prefix(range.upperBound.advanced(by: 1)) }
subscript(_ range: PartialRangeUpTo) -> SubSequence { prefix(range.upperBound) }
subscript(_ range: PartialRangeFrom) -> SubSequence { suffix(Swift.max(0, count-range.lowerBound)) }
}
extension LosslessStringConvertible {
var string: String { .init(self) }
}
extension BidirectionalCollection {
subscript(safe offset: Int) -> Element? {
guard !isEmpty, let i = index(startIndex, offsetBy: offset, limitedBy: index(before: endIndex)) else { return nil }
return self[i]
}
}
Testing
let test = "Hello USA