So I have this code finding Ranges substrings by splitting new lines:
let string = "hello\nhello"
let rangesSplittedByLines: [Range] = string.split(separator: "\n").compactMap {
return string.range(of: $0)
}
But I need those ranges as NSRange.
How would you get NSRange array of all substrings?
In the closure create an
NSRangefromRange<String.Index>But there is another problem. The code returns
[{0, 5}, {0, 5}]becauserange(of:returns always the range of the first match.This fixes the problem, it slices the string by moving the start index to the position after the most recent match
And there is no reason to bridge
StringtoNSStringexplicitly.But as you want nsranges anyway Regular Expression like in Martin’s answer is much more efficient.