Skip to content

Instantly share code, notes, and snippets.

@ishowta
Last active July 22, 2019 14:24
Show Gist options
  • Save ishowta/8bcecb29e1ee66f6bc915ecfa975e116 to your computer and use it in GitHub Desktop.
Save ishowta/8bcecb29e1ee66f6bc915ecfa975e116 to your computer and use it in GitHub Desktop.
Swift string random access extension (fuckin' slow)
// Too bad extension. Bad I think it is the best way.
extension String {
subscript(index: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: index)]
}
subscript(bounds: CountableRange<Int>) -> Substring {
return self[index(at: bounds.lowerBound)..<index(at: bounds.upperBound)]
}
subscript(bounds: CountableClosedRange<Int>) -> Substring {
return self[index(at: bounds.lowerBound)...index(at: bounds.upperBound)]
}
subscript(bounds: PartialRangeUpTo<Int>) -> Substring {
return self[..<index(at: bounds.upperBound)]
}
subscript(bounds: PartialRangeThrough<Int>) -> Substring {
return self[...index(at: bounds.upperBound)]
}
subscript(bounds: PartialRangeFrom<Int>) -> Substring {
return self[index(at: bounds.lowerBound)...]
}
subscript(bounds: CountableRange<Int>) -> String {
return String(self[index(at: bounds.lowerBound)..<index(at: bounds.upperBound)])
}
subscript(bounds: CountableClosedRange<Int>) -> String {
return String(self[index(at: bounds.lowerBound)...index(at: bounds.upperBound)])
}
subscript(bounds: PartialRangeUpTo<Int>) -> String {
return String(self[..<index(at: bounds.upperBound)])
}
subscript(bounds: PartialRangeThrough<Int>) -> String {
return String(self[...index(at: bounds.upperBound)])
}
subscript(bounds: PartialRangeFrom<Int>) -> String {
return String(self[index(at: bounds.lowerBound)...])
}
func index(at offset: Int) -> String.Index {
return index(startIndex, offsetBy: offset)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment