Skip to content

Instantly share code, notes, and snippets.

@brunogama
Created February 12, 2025 10:51
Show Gist options
  • Save brunogama/4d41d19f56274c40d7a3f9f35458235e to your computer and use it in GitHub Desktop.
Save brunogama/4d41d19f56274c40d7a3f9f35458235e to your computer and use it in GitHub Desktop.
extension String {
/// Returns an array of substrings based on the provided ranges
/// - Parameter ranges: Array of ranges to slice the string
/// - Returns: Array of sliced strings
func sliced(_ ranges: [Range<Int>]) -> [String] {
ranges.map { range in
let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound)
let endIndex = self.index(self.startIndex, offsetBy: range.upperBound)
return String(self[startIndex..<endIndex])
}
}
/// Returns an array of substrings based on the provided ranges with safe bounds
/// - Parameter ranges: Array of ranges to slice the string
/// - Returns: Array of safely sliced strings
func safeSliced(_ ranges: [Range<Int>]) -> [String] {
ranges.map { range in
let safeLowerBound = max(0, range.lowerBound)
let safeUpperBound = min(self.count, range.upperBound)
guard safeLowerBound < self.count, safeUpperBound > 0, safeLowerBound < safeUpperBound else {
return ""
}
let startIndex = self.index(self.startIndex, offsetBy: safeLowerBound)
let endIndex = self.index(self.startIndex, offsetBy: safeUpperBound)
return String(self[startIndex..<endIndex])
}
}
}
// Example usage:
let text = "Hello, World!"
let ranges = [0..<5, 7..<12]
let sliced = text.sliced(ranges) // ["Hello", "World"]
let unsafeRanges = [-2..<5, 7..<20]
let safeSliced = text.safeSliced(unsafeRanges) // ["Hello", "World!"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment