快速字符串范围 - 有没有更简单的方法来定义字符串范围?



我考虑是否有一些更简单的方法来定义字符串范围,我尝试使用一些需要范围的函数,而快速范围似乎非常不可读且很长。

title.startIndex..<title.index(title.startIndex, offsetBy: 1)

只是说我只想搜索这个字符串的 [0,1( 个字符

label.text = title.replacingOccurrences(of: "n", with: "", options: .caseInsensitive, range: title.startIndex..<title.index(title.startIndex, offsetBy: 1) )

实际上没有一种简洁的方法来指定String范围。

你可以用一个扩展让它变得更好一点:

extension StringProtocol {
func range(_ ir: Range<Int>) -> Range<String.Index> {
return self.index(self.startIndex, offsetBy: ir.lowerBound) ..< self.index(self.startIndex, offsetBy: ir.upperBound)
}
}

然后

title.startIndex..<title.index(title.startIndex, offsetBy: 1)

成为

title.range(0..<1)

注意:请注意指定有效范围,否则这将崩溃,就像您在示例中使用了超出字符串末尾的偏移量一样。

问题是replacingOccurrencesOf是一种Cocoa Objective-C NSString方法,所以你最终会在Range的String概念和NSRange的NSString概念之间进行类型阻抗不匹配。最简单的解决方案是留在 NSString 世界中:

label.text = (title as NSString).replacingOccurrences(
of: "n", with: "", options: .caseInsensitive, 
range: NSRange(location: 0, length: 2))

否则,我同意vacawama的扩展想法:

extension String {
func range(_ start:Int, _ count:Int) -> Range<String.Index> {
let i = self.index(start >= 0 ?
self.startIndex :
self.endIndex, offsetBy: start)
let j = self.index(i, offsetBy: count)
return i..<j
}
func nsRange(_ start:Int, _ count:Int) -> NSRange {
return NSRange(self.range(start,count), in:self)
}
}

那你可以说

label.text = title.replacingOccurrences(
of: "n", with: "", options: .caseInsensitive, 
range: title.range(0,2))

最新更新