如何转换NSRange中的范围?

我正在快速更新代码3。在将Range转换为NSRange时出错。如何迅速3做到这一点?

func nsRange(_ range : Range<String.Index>) -> NSRange {

let utf16from = String.UTF16View.Index(range.lowerBound, within: utf16)

let utf16to = String.UTF16View.Index(range.upperBound, within: utf16)

return NSRange(location: utf16.startIndex.distanceTo(utf16from), length: utf16from.distanceTo(utf16to))

}

回答:

import Foundation

extension RangeExpression where Bound == String.Index {

func nsRange<S: StringProtocol>(in string: S) -> NSRange { .init(self, in: string) }

}


let string = "Hello USA ???????? !!! Hello World !!!"

if let nsRange = string.range(of: "Hello World")?.nsRange(in: string) {

(string as NSString).substring(with: nsRange) // "Hello World"

}

您还可以创建相应的nsRange(of:)扩展方法StringProtocol

extension StringProtocol {

func nsRange<S: StringProtocol>(of string: S, options: String.CompareOptions = [], range: Range<Index>? = nil, locale: Locale? = nil) -> NSRange? {

self.range(of: string,

options: options,

range: range ?? startIndex..<endIndex,

locale: locale ?? .current)?

.nsRange(in: self)

}

func nsRanges<S: StringProtocol>(of string: S, options: String.CompareOptions = [], range: Range<Index>? = nil, locale: Locale? = nil) -> [NSRange] {

var start = range?.lowerBound ?? startIndex

let end = range?.upperBound ?? endIndex

var ranges: [NSRange] = []

while start < end,

let range = self.range(of: string,

options: options,

range: start..<end,

locale: locale ?? .current) {

ranges.append(range.nsRange(in: self))

start = range.lowerBound < range.upperBound ? range.upperBound :

index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex

}

return ranges

}

}


let string = "Hello USA ???????? !!! Hello World !!!"

if let nsRange = string.nsRange(of: "Hello World") {

(string as NSString).substring(with: nsRange) // "Hello World"

}

let nsRanges = string.nsRanges(of: "Hello")

print(nsRanges) // "[{0, 5}, {19, 5}]\n"

以上是 如何转换NSRange中的范围? 的全部内容, 来源链接: utcz.com/qa/410189.html

回到顶部