Skip to content

Instantly share code, notes, and snippets.

@Brimizer
Created September 8, 2014 06:44
Show Gist options
  • Save Brimizer/62fcf613bc462d0beb99 to your computer and use it in GitHub Desktop.
Save Brimizer/62fcf613bc462d0beb99 to your computer and use it in GitHub Desktop.
Swift Convert Range<Int> to Range<String.Index>
// Public domain.
// Free to use.
// Use like this:
var world = "Hello, world!"
let convertedRange = world.convertRange(0..<5)
world.removeRange(convertedRange)
// Converts a regular range (0..5) to a proper String.Index range.
extension String {
public func convertRange(range: Range<Int>) -> Range<String.Index> {
let startIndex = advance(self.startIndex, range.startIndex)
let endIndex = advance(startIndex, range.endIndex - range.startIndex)
return Range<String.Index>(start: startIndex, end: endIndex)
}
}
@Jasonbit
Copy link

A Swift 2.2 update for this is:

1  extension String {
2    public func convertRange(range: Range<Int>) -> Range<String.Index> {
3        let startIndex = self.startIndex.advancedBy(range.startIndex)
4       let endIndex = startIndex.advancedBy(range.endIndex - range.startIndex)
5      return Range<String.Index>(start: startIndex, end: endIndex)
6    }
7  }

Of course, you will get a compiler warning on line 5 since this is deprecated and will be removed in Swift 3.

@frogcjn
Copy link

frogcjn commented Dec 12, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment