Skip to content

Instantly share code, notes, and snippets.

@azonov
Created November 4, 2023 08:54
Show Gist options
  • Save azonov/684b3d47454527a4bdaf7ac76ae32591 to your computer and use it in GitHub Desktop.
Save azonov/684b3d47454527a4bdaf7ac76ae32591 to your computer and use it in GitHub Desktop.
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 = "🧗🏾‍♂️iOS Broadcast 🚀🗿"
print(text[0]) // 🧗🏾‍♂️
print(text[-1]) // 🗿
print(text[1]) // i
print(text[5...13]) // Broadcast
print(text[5...40]) // ❌ EXC_BREAKPOINT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment