Hello.
I have been using Range(range: NSRange, in: String) to convert an NSRange to a Range<String.Index>. It works for normal string but failed in some cases, like:
let s = "”\r\n\r\n[attach]457867[/attach]\r\n\r\n\r\n"
let range = NSRange(location: 4, length: 1)
let textRange = Range(range, in: s) // it's nil
It should work for that range but actually not. Meanwhile, I can't find the documentation of that method.
Using a Range<String.Index> always work.
Do all of the cases where it doesn’t work involve “\r\n”, or is that only true in this one particular case? I ask because that sequence is treated as a single grapheme cluster (Character in Swift parlance), and I wouldn’t be terribly surprised if that caused a bug.
(Also, what version of Swift is this? Which platform?)
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