Last active
December 14, 2024 04:39
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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