Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save imjhk03/13c3fb4181fd0b3b3d97e272e35837d3 to your computer and use it in GitHub Desktop.

Select an option

Save imjhk03/13c3fb4181fd0b3b3d97e272e35837d3 to your computer and use it in GitHub Desktop.
Access Swift.String character by Int subscript. https://twitter.com/krzyzanowskim/status/1720190374956732789
extension StringProtocol {
subscript(_ offset: Int) -> String.Element {
if offset >= 0 {
self[index(startIndex, offsetBy: offset)]
} else {
self[index(endIndex, offsetBy: offset)]
}
}
subscript(_ offsetRange: Range<Int>) -> SubSequence {
self[Range<String.Index>(
uncheckedBounds: (
lower: index(startIndex, offsetBy: offsetRange.lowerBound),
upper: index(startIndex, offsetBy: offsetRange.upperBound)
)
)]
}
subscript(_ offsetRange: ClosedRange<Int>) -> SubSequence {
self[ClosedRange<String.Index>(
uncheckedBounds: (
lower: index(startIndex, offsetBy: offsetRange.lowerBound),
upper: index(startIndex, offsetBy: offsetRange.upperBound)
)
)]
}
}
let text = "abc🫣def"
print(text[4]) // d
print(text[-1]) // f
print(text[0..<4]) // abc🫣
print(text[0...4]) // abc🫣d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment