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
To obtain character index: