(This question is motivated by Swift substring crash on reversed on Stack Overflow.)
Apparently, iterating over a ReversedCollection<String.SubSequence>
can crash if the substring starts within an extended grapheme cluster:
let string = "abc\r\nxyz"
let idx = string.range(of: "\n")!.lowerBound
let substring = string[idx...]
let rev = substring.reversed()
let revString = String(rev)
// 💣 Fatal error: Out of bounds: index < startIndex
The same crash happens with any of the following:
let arr = Array(rev)
for c in rev { print(c) }
print(rev.last!)
Is this a bug or the expected behavior? If it is to be expected, what would be the correct approach to avoid the crash? Do I have to check explicitly if the character (here: "\n") is part of an extended grapheme cluster (here: "\r\n")?