Reputation: 5323
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
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