How can I get the nth character of a string? I tried bracket([]
) accessor with no luck.
var string = \"Hello, world!\"
var firstChar = string[
String
's indices
propertyAs variation of @LeoDabus nice answer, we may add an additional extension to DefaultIndices with the purpose of allowing us to fall back on the indices
property of String
when implementing the custom subscripts (by Int
specialized ranges and partial ranges) for the latter.
extension DefaultIndices {
subscript(at: Int) -> Elements.Index { index(startIndex, offsetBy: at) }
}
// Moving the index(_:offsetBy:) to an extension yields slightly
// briefer implementations for these String extensions.
extension String {
subscript(range: Range) -> SubSequence {
let start = indices[range.lowerBound]
return self[start..) -> SubSequence {
let start = indices[range.lowerBound]
return self[start...indices[start...][range.count]]
}
subscript(range: PartialRangeFrom) -> SubSequence {
self[indices[range.lowerBound]...]
}
subscript(range: PartialRangeThrough) -> SubSequence {
self[...indices[range.upperBound]]
}
subscript(range: PartialRangeUpTo) -> SubSequence {
self[..
Thanks @LeoDabus for the pointing me in the direction of using the indices
property as an(other) alternative to String
subscripting!