Martin
(Martin R)
1
(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")?
2 Likes
eskimo
(Quinn “The Eskimo!”)
2
You should definitely file a bug about this. Regardless of whether there’s a ‘good’ reason for it, it’s a really sharp edge case that needs to be smoothed off.
Please post your bug number, just for the record.
Share and Enjoy
Quinn “The Eskimo!” @ DTS @ Apple
Martin
(Martin R)
3
1 Like