I try to get the distance between a string's startIndex and another index, but get the following error in the first loop iteration. The code actually works with most string, but with some it crashes.
fatal error: cannot increment endIndex
let content = NSMutableAttributedString(string: rawContent, attributes: attrs)
var startIndex = content.string.characters.startIndex
while true {
let searchRange = startIndex..<rawContent.characters.endIndex
if let range = rawContent.rangeOfString("\n", range: searchRange) {
let index = rawContent.characters.startIndex.distanceTo(range.startIndex)
startIndex = range.startIndex.advancedBy(1)
rawContent.replaceRange(range, with: "*")
content.addAttribute(
NSForegroundColorAttributeName,
value: UIColor.redColor(),
range: NSMakeRange(index, 1))
}
else {
break
}
}
content.replaceCharactersInRange(NSMakeRange(0, content.length), withString: rawContent)
content is NSMutableAttributedString and when the app crashes the variables have the following values:
range.startIndex: 164
content.string.characters.startIndex: 0
content.string.characters.endIndex: 437,
content.string.characters.count: 435
I don't understand why the error message says about increasing endIndex when I'm trying to calculate the distance from the startIndex and anotherIndex is less than the string length.
\ncharacters and replacing them withspacecharacters? Why not just usereplaceOcurrencesOfString?