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?
Its because
Swift
treats\r\n
as one character,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.