Last active
September 18, 2024 21:47
-
-
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
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 { | |
/// 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 { | |
let start = self.index(startIndex, offsetBy: range.lowerBound) | |
let end = self.index(start, offsetBy: range.upperBound - range.lowerBound) | |
return self[start..<end] | |
} | |
/// str[1...3] | |
subscript(_ range: ClosedRange<Int>) -> SubSequence { | |
let start = self.index(startIndex, offsetBy: range.lowerBound) | |
let end = self.index(start, offsetBy: range.upperBound - range.lowerBound) | |
return self[start...end] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment