How to convert Range<String.Index> to NSRange? [duplicate]

余生长醉 提交于 2019-12-12 05:25:39

问题


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?


回答1:


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:

public extension NSRange {
    private init(string: String, lowerBound: String.Index, upperBound: String.Index) {
        let utf16 = string.utf16

        let lowerBound = lowerBound.samePosition(in: utf16)
        let location = utf16.distance(from: utf16.startIndex, to: lowerBound)
        let length = utf16.distance(from: lowerBound, to: upperBound.samePosition(in: utf16))

        self.init(location: location, length: length)
    }

    public init(range: Range<String.Index>, in string: String) {
        self.init(string: string, lowerBound: range.lowerBound, upperBound: range.upperBound)
    }

    public init(range: ClosedRange<String.Index>, in string: String) {
        self.init(string: string, lowerBound: range.lowerBound, upperBound: range.upperBound)
    }
}


来源:https://stackoverflow.com/questions/45493826/how-to-convert-rangestring-index-to-nsrange

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!