Saurav Nagpal
Saurav Nagpal

Reputation: 1267

Swift substring crash on reversed (Need a Reason)

I stuck facing a strange issue with the following code:

var testString = """
This is test \r\n Pass        Fail
"""

if let charIndex = testString.range(of: "\n")?.lowerBound {
    let substring = testString[charIndex...]
    print(substring.reversed())
    var revereseString = String(substring.reversed())
}

My Application crashed with the following error: Fatal error: Out of bounds: index < startIndex

Can anybody Explain why it is crashing in specific case. If I remove "\r" from the string it will not crash. There are multiple way to fix the issue but I want to know why it is crashing?

Upvotes: 1

Views: 181

Answers (1)

Mohmmad S
Mohmmad S

Reputation: 5098

Its because Swift treats \r\n as one character,

let foo = "\r"
foo.count // 1
let fee = "\n"
fee.count // 1
let bee = "\r\n"
bee.count // 1

One of your solutions is putting a space between them \r \n and that would make it run because now they're 2 different characters.

How ?

The buffer registered them in the variable as one character yet treated in the .range iterator as two characters which causes the crash.

Upvotes: 2

Related Questions