Skip to content

Instantly share code, notes, and snippets.

@azonov
Created November 4, 2023 08:54
Show Gist options
  • Select an option

  • Save azonov/684b3d47454527a4bdaf7ac76ae32591 to your computer and use it in GitHub Desktop.

Select an option

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