Return 使用范围在 Swift 中的属性字符串的子字符串

Return substring from attributed string using range in Swift

我正在尝试使用范围从字符串中获取子字符串,但不幸的是。到处搜索,我在 Swift 中找不到完成这个看似简单的任务的方法。该范围采用从委托方法获得的 NSRange 形式。

在Objective-c中,如果你有一个范围,你可以这样做:

NSString * text = "Hello World";
NSString *sub = [text substringWithRange:range];

根据 ,以下应该适用于 Swift:

let mySubstring = text[range]  // play
let myString = String(mySubstring)

但是,当我尝试这样做时,出现错误:

Cannot subscript a value of type 'String' with an index of type 'NSRange' (aka '_NSRange')

我认为问题可能与使用 NSRange 而不是范围有关,但我不知道如何让它工作。感谢您的任何建议。

请再读一遍你的链接问题。

您会注意到 Swift 中的字符串不适用于 Range<Int>,但适用于 Range<String.Index>,绝对不适用于 NSRange

在字符串上使用范围的示例:

let text = "Hello world"
let from = text.index(after: text.startIndex)
let to = text.index(from, offsetBy: 4)
text[from...to] // ello

问题是你不能使用 NSRange 下标 String,你必须使用 Range。尝试以下操作:

let newRange = Range(range, in: text)
let mySubstring = text[newRange]
let myString = String(mySubstring)