Created
September 8, 2014 06:44
-
-
Save Brimizer/62fcf613bc462d0beb99 to your computer and use it in GitHub Desktop.
Swift Convert Range<Int> to Range<String.Index>
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
// 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) | |
} | |
} |
Swift 4.0 Complete Solution:
https://github.com/frogcjn/OffsetIndexableCollection-String-Int-Indexable-
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A Swift 2.2 update for this is:
Of course, you will get a compiler warning on line 5 since this is deprecated and will be removed in Swift 3.