Background
I am writing a syntax marker kind of tool in swift. I parse the text, then save the marking info, I call it a Mark
(a name as a String
with a range as a Range<String.Index>
). I choose the Range<String.Index>
over NSRange
for future proof the interface.
Problem
In order to support on the fly parsing, I need to be able to manipulate the range. E.g. the text has been edited in a text view, instead of re-parse the whole text, I want to only parse the edited chunk for performance gain. The problem is how do I shift the Marks
after the edited range? Since they are never changed, the only thing that changes are the ranges.
I've tried the index function like this:
let newStartIndex = string.index(oldStartIndex, offsetBy: changeInLength)
But the problem with that is that the oldStartIndex
is very possible to be out of bound of the new string
. Then it will throw a fatal error. Even if I kept a copy of the old text and use that to do the index offset, I think the old index within the modified string might not necessarily maintain it's integrity.
With NSRange
, things are much simpler, just shift the location
property. But the key here is to future proof the interface by using Range<String.Index>
.