In Swift 3.0 (NS)Scanner, string property returns the string being parsed and scanLocation returns the current scan location. I'm trying to extract the parsed text:
var parsedText: String {
return string.substring(to: string.index(string.startIndex, offsetBy: scanLocation))
}
This code crashes when string contains multibyte characters. It turned out that scanLocation returns number of utf16 units, not number of characters parsed.
How to convert scanLocation (code units) into character index?
Playground for experimenting:
let scanner = Scanner(string: "Hello")
scanner.scanString("Hello", into: nil)
print(scanner.scanLocation) // Returns 7 instead of 6
To obtain character index:
To retrieve parsed text:
Bonus: when reporting errors, you'll probably want to print current line and column as well: