Skip to content

Instantly share code, notes, and snippets.

@chefnobody
Created February 2, 2018 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chefnobody/cfdd66f6ecb976817553d56c8f07bee6 to your computer and use it in GitHub Desktop.
Save chefnobody/cfdd66f6ecb976817553d56c8f07bee6 to your computer and use it in GitHub Desktop.
Swift String extension for subscripting with `Int` rather than `String.Index`
// This doesn't consider multi-code Unicode characters like 🤖
extension String {
subscript(range: Range<Int>) -> String {
// Convert Int range to String.Index-based range
let begin = String.Index(encodedOffset: range.lowerBound)
let end = String.Index(encodedOffset: range.upperBound)
return String(self[begin...end])
}
}
"PIZZA"[3..<4]
"PIZZA"[0..<1]
"🍔BURGERTIME"[0..<0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment