[英]Swift String Range - Is there easier way to define string ranges?
我考慮是否有一些更簡單的方法來定義字符串范圍我嘗試使用一些需要范圍的 function 和 swift 范圍似乎令人難以置信的不可讀和長。
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)
注意:請注意指定有效范圍,否則會崩潰,就像您在示例中使用超出字符串末尾的偏移量一樣。
問題是 replaceOccurrencesOf 是replacingOccurrencesOf
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.