Skip to content

Instantly share code, notes, and snippets.

@capnslipp
Last active April 20, 2017 02:24
Show Gist options
  • Save capnslipp/139a1b4851881244972aee5dd8b89846 to your computer and use it in GitHub Desktop.
Save capnslipp/139a1b4851881244972aee5dd8b89846 to your computer and use it in GitHub Desktop.
Swift String extensions for shorthand (Ruby-like) indexing
//: Playground - noun: a place where people can play
import Swift
var str = "Hello, playground"
extension String
{
func index(atOffset offset:String.IndexDistance) -> String.Index {
return index(offset >= 0 ? self.startIndex : self.endIndex, offsetBy: offset)
}
subscript(atOffset offset:String.IndexDistance) -> Character {
return self[self.index(atOffset: offset)]
}
subscript(withinOffsets offsetRange:Range<String.IndexDistance>) -> String {
return self[fromOffset: offsetRange.lowerBound, toOffset: offsetRange.upperBound]
}
subscript(fromOffset lowerOffset:String.IndexDistance, toOffset upperOffset:String.IndexDistance) -> String {
let indexes = (
lower: self.index(atOffset: lowerOffset),
upper: self.index(atOffset: upperOffset)
)
return self[indexes.lower ..< indexes.upper]
}
subscript(withinOffsets offsetRange:ClosedRange<String.IndexDistance>) -> String {
return self[fromOffset: offsetRange.lowerBound, throughOffset: offsetRange.upperBound]
}
subscript(fromOffset lowerOffset:String.IndexDistance, throughOffset upperOffset:String.IndexDistance) -> String {
let indexes = (
lower: self.index(atOffset: lowerOffset),
upper: self.index(atOffset: upperOffset)
)
return self[indexes.lower ... indexes.upper]
}
}
str[atOffset: -1] // "d"
str[atOffset: -2] // "n"
str[atOffset: 0] // "H"
str[atOffset: 1] // "e"
str[withinOffsets: 1 ... 10] // "ello, play"
str[withinOffsets: -10 ... -1] // "playground"
str[fromOffset: 1, throughOffset: -1] // "ello, playground"
str[withinOffsets: 1 ..< 10] // "ello, pla"
str[withinOffsets: -10 ..< -1] // "playgroun"
str[fromOffset: 1, toOffset: -1] // "ello, playgroun"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment