Skip to content

Instantly share code, notes, and snippets.

@krzyzanowskim
Last active July 3, 2024 07:00
Show Gist options
  • Save krzyzanowskim/9b54db40072628d0a0c37d75ee33f84b to your computer and use it in GitHub Desktop.
Save krzyzanowskim/9b54db40072628d0a0c37d75ee33f84b to your computer and use it in GitHub Desktop.
Swift Core Team going to hate you https://x.com/krzyzanowskim/status/1807853935064986109
extension StringProtocol {
/// str[NSRange(location:0, length: 9)]
subscript(_ range: NSRange) -> SubSequence {
guard let stringRange = Range<String.Index>(range, in: self) else {
fatalError("String index is out of range")
}
return self[stringRange]
}
/// str[0]
subscript(_ characterIndex: Int) -> Element? {
self[self.index(startIndex, offsetBy: characterIndex)]
}
/// str[1..<3]
subscript(_ range: Range<Int>) -> SubSequence {
self[NSRange(location: range.lowerBound, length: range.upperBound - range.lowerBound)]
}
/// str[1...3]
subscript(_ range: ClosedRange<Int>) -> SubSequence {
self[NSRange(location: range.lowerBound, length: range.upperBound - range.lowerBound + 1)]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment