简体   繁体   English

Swift 字符串范围 - 是否有更简单的方法来定义字符串范围?

[英]Swift String Range - Is there easier way to define string ranges?

I consider if there are some easier ways to define string ranges I tried to use some function that need ranges and swift ranges seems to be incredibly unreadable and long.我考虑是否有一些更简单的方法来定义字符串范围我尝试使用一些需要范围的 function 和 swift 范围似乎令人难以置信的不可读和长。

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

and just to say I want to search only in [0,1) characters of this string只是说我只想在这个字符串的 [0,1) 个字符中搜索

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

There isn't really a concise way to specify a String range.实际上并没有一种简洁的方法来指定String范围。

You could make it a bit nicer with an extension:你可以通过扩展使它更好一点:

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)
    }
}

Then然后

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

becomes变成

title.range(0..<1)

Note: Be careful to specify a valid range, or this will crash, just like if you had used an offset beyond the end of your string in your example.注意:请注意指定有效范围,否则会崩溃,就像您在示例中使用超出字符串末尾的偏移量一样。

The problem is that replacingOccurrencesOf is an Cocoa Objective-C NSString method, so you end up with type impedance mismatch between the String notion of a Range and the NSString notion of an NSRange.问题是 replaceOccurrencesOf 是replacingOccurrencesOf Objective-C NSString 方法,因此您最终会导致 Range 的 String 概念与 NSRange 的 NSString 概念之间的类型阻抗不匹配。 The simplest solution is to stay in the NSString world:最简单的解决方案是留在 NSString 世界中:

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

Otherwise I agree with vacawama's idea of an extension:否则,我同意 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)
    }
}

Then you can say然后你可以说

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM