fatal error: cannot increment beyond endIndex

I have a string with lots of spaces in it. When I try to remove characters from the start of my string it works until I run into a blank space:


var str = label.stringValue
           
            let c = str.characters
           
            let r = c.index(c.startIndex, offsetBy: 5)..<c.index(c.endIndex, offsetBy: 0)
           
            let substring = str[r]
           
            print(substring)



My label.stringValue is "Pixel Film Studios - Test1"


I can remove the first 5 characters successfully but when I try and remove the 6th character it throws a fatal error. I want to remove the first 21 characters so that I am jsut left with "Test1" as my label's stringValue? What do I need to do to be able to offset characters and spaces?

Replies

Could you post the actual code that compiles and where exactly you get the crash.

In general it’s better to avoid walking through a string character by character. Rather, you should try to implement your string processing in terms of higher-level constructs. For example, you wrote:

I want to remove the first 21 characters so that I am jsut left with "Test1" as my label's stringValue?

which you can do in a variety of different ways:

  • if the prefix can vary but the separator is fixed, you can search for the separator

  • if the prefix is fixed, you can search for the prefix, but anchor that search at the start

  • if you know the suffix can’t contain a specific character, you can search backwards from that

  • you can split the string based on the separator and then extract parts

Pasted in below is code to do each of these.

There’s a bunch of advantages to moving to a higher-level abstraction, including:

  • you write less code

  • that code is easier to read

  • that code is more likely to work well with arbitrary Unicode

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
import Foundation

let str = "Pixel Film Studios - Test1"

if let r = str.range(of: " - ") {
    print(str.substring(from: r.upperBound))
} else {
    print("separator not found")
}
// prints 'Test1'

if let r = str.range(of: "Pixel Film Studios - ", options: [.anchored]) {
    print(str.substring(from: r.upperBound))
} else {
    print("separator not found")
}
// prints 'Test1'

if let r = str.range(of: " ", options: [.backwards]) {
    print(str.substring(from: r.upperBound))
} else {
    print("separator not found")
}
// prints 'Test1'

let parts = str.components(separatedBy: " - ")
print(parts)
// prints '["Pixel Film Studios", "Test1"]'