This question already has an answer here:
- NSRange from Swift Range? 11 answers
How do I convert Range<String.Index>
to NSRange
in Swift (< 4) without first converting the String
to an NSString
?
The reason I want to do this is that I want to set a UITextView
's selectedText
property using a Range<String.Index>
value.
Alternative solution: How do I set UITextInput.selectedTextRange
with a Range<String.Index>
value?
Use String.Index's samePosition(in:) method with the string's UTF16 view. NSString uses UTF16, so the UTF16 indexes should be identical to the indexes NSString expects for the NSRange.
EDIT: