Skip to content

Instantly share code, notes, and snippets.

@krzyzanowskim
Last active December 8, 2023 18:26
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save krzyzanowskim/7c688449cbeaa857da3f50f019bbd3a5 to your computer and use it in GitHub Desktop.
Save krzyzanowskim/7c688449cbeaa857da3f50f019bbd3a5 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