使用 Swift 中的范围从属性字符串返回子字符串



我试图使用该范围从字符串中获取子字符串,但没有运气。在搜索了高处和低处之后,我找不到一种方法来在 Swift 中完成这个看似简单的任务。该范围采用从委托方法获得的 NSRange 的形式。

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

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

根据这个答案,以下内容应该在 Swift 中工作:

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

但是,当我尝试此操作时,出现错误:

不能使用类型的索引下标类型为"字符串"的值 "NSRange"(又名"_NSRange"(

我认为这个问题可能与使用 NSRange 而不是范围有关,但我无法弄清楚如何让它工作。 感谢您的任何建议。

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

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

请再次阅读您链接的问题。

你会注意到 Swift 中的 String 不适用于 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

最新更新