Substring enumeration

Hi, currently if we want to enumerate all substrings/range of a string in a string rather than just the first one, we ought go with something like this:

var lo = text.startIndex
            while lo < text.endIndex {
                guard
                    let range = text[lo..<text.endIndex].range(of: pattern)
                else { break }
                
                result.append(text[range])
                lo = range.upperBound
                // eventually add logic to break the loop earlier 
            }

Wouldn't it be better to be able to do something like this natively:

text.enumerateRanges(of: pattern) { range, stop in 
    // do what you have to with the given range of the occurrence, 
    // eventually set stop to true in order to stop the enumeration.
}

There are some interesting algorithms for substring lookups as Knutt-Morris-Pratt, Boyer-Moore or Rabin-Karp.
I've being trivially playing around with them and it looks like they also perform better than doing that while-loop which leverages on string's range(of:) instance method.
I've put up something in a swift package, though if you guys are interested you might as well check it out here.
Thanks.

1 Like