AP.
AP.

Reputation: 5323

convert unicodeScalars index to character index in a swift string

I have a parser that use the unicodeScalars view of a string to calculate indexes. From the result of the parser. I have an NSTextView where I would like to place the caret depending of the result of the parser. Unfortunately, the selectedRange of the NSTextView is expecting a character index and not an unicodeScalar Index.

How can I convert the index from unicodeScalars to Characters?

Upvotes: 0

Views: 373

Answers (1)

Martin R
Martin R

Reputation: 539845

The different string views share a common String.Index, and NSRange(_:in:) can be used to convert a String range to NSRange (which is what selectedRange needs). Example:

let str = "πŸ‡©πŸ‡ͺabπŸ˜€cde"
if let idx = str.unicodeScalars.firstIndex(of: "πŸ˜€") {
    let nsRange = NSRange(idx...idx, in: str)

    print(nsRange) // {6, 2}
    print((str as NSString).substring(with: nsRange)) // πŸ˜€
}

Upvotes: 1

Related Questions