Forked from krzyzanowskim/StringOffsetSubscript.swift
Created
November 3, 2023 07:23
-
-
Save gopalkrishnareddy/723a6b8ec064c5e65c8bb07f826998ba 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