How to convert Range to NSRange? [duplicat

2019-08-26 22:24发布

This question already has an answer here:

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条回答
Root(大扎)
2楼-- · 2019-08-26 22:35

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)
    }
}
查看更多
登录 后发表回答