Skip to content

Instantly share code, notes, and snippets.

@pauljohanneskraft
Last active June 25, 2019 10:35
Show Gist options
  • Save pauljohanneskraft/cfa586254e6c8b2a9ffb1580b58eff2b to your computer and use it in GitHub Desktop.
Save pauljohanneskraft/cfa586254e6c8b2a9ffb1580b58eff2b to your computer and use it in GitHub Desktop.
A Swift Int-subscript for Strings

String subscripts

Implementation of string subscripts using Int.

var str = "πŸ˜‚πŸ˜…πŸ˜ŠπŸ˜œπŸ˜"
str[0..<2] = ""
print(str)
// Prints "😊😜😝"
extension String {
subscript(index: String.CharacterView.Index) -> Character {
get { return self.characters[index] }
set {
self.characters.remove(at: index)
self.characters.insert(newValue, at: index)
}
}
subscript(range: Range<Index>) -> String {
@warn_unused_result get { return String(self.characters[range]) }
set { self.characters.replaceSubrange(range, with: newValue.characters) }
}
@warn_unused_result
func getIndex(_ v: Int) -> Index {
return self.index(startIndex, offsetBy: v)
}
@warn_unused_result
func getIndexRange(_ r: CountableRange<Int>) -> Range<Index> {
let start = getIndex(r.lowerBound)
let end = index(start, offsetBy: r.count)
return start..<end
}
subscript(index: Int) -> Character {
@warn_unused_result get { return self[getIndex(index)] }
set { self[getIndex(index)] = newValue }
}
subscript(range: CountableRange<Int>) -> String {
@warn_unused_result get { return self[getIndexRange(range)] }
set { self[getIndexRange(range)] = newValue }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment