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 } | |
} | |
} |