我正在更新swift 3中的代码。将Range转换为NSRange时出错。如何在swift 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))
}
答案 0 :(得分:64)
Xcode 10.2•Swift 5
extension StringProtocol {
func nsRange(from range: Range<Index>) -> NSRange {
return .init(range, in: self)
}
}
let string = "Hello USA !!! Hello World !!!"
if let range = string.range(of: "Hello World") {
let nsRange = string.nsRange(from: range)
(string as NSString).substring(with: nsRange) // "Hello World"
}
您还可以创建扩展nsRange(of:)
的相应StringProtocol
方法:
extension StringProtocol {
func nsRange(of string: Self, options: String.CompareOptions = [], range: Range<Index>? = nil, locale: Locale? = nil) -> NSRange? {
guard let range = self.range(of: string, options: options, range: range ?? startIndex..<endIndex, locale: locale ?? .current) else { return nil }
return .init(range, in: self)
}
func nsRanges(of string: Self, 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(.init(range, in: self))
start = range.upperBound
}
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"