简体   繁体   中英

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.

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

and just to say I want to search only in [0,1) characters of this string

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.

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. The simplest solution is to stay in the NSString world:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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