`Range(range: NSRange, in: String)` seems broken

As @beccadax suggested, this isn’t a bug in Swift, but due to the fact that \r\n is a single grapheme cluster/Character. The NSRange starting at location: 4 falls in the middle of the grapheme cluster "\r\n" in your sample string. So it’s not a valid position for a String range. The correct range for that grapheme cluster is NSRange(location: 3, length: 2):

let s = "”\r\n\r\n[attach]457867[/attach]\r\n\r\n\r\n"
let range = NSRange(location: 3, length: 2)
let textRange = Range(range, in: s) // non-nil
2 Likes