Add StringProtocol.suffix(after prefix: StringProtocol) -> Substring?

The idea is to add a helper for parser combinator-like things. Currently, I have to do something like the following:

extension StringProtocol {
    func suffix(after prefix: StringProtocol) -> Substring? {
        guard hasPrefix(prefix) else { return nil }
        let suffixIndex = self.index(startIndex, offsetBy: prefix.characters.count)
        return self[suffixIndex...]

(Modified from

This has two expensive string operations, that could be reduced to one if the hasPrefix call included the result of the computation. I hope that the String interface hasn’t been set in stone yet, and that I’ll be able to sneak this in.

An alternative would be to provide an optional index after the prefix instead of the substring.

Ideally, this would be a bit like the arithmetic operations that have hidden variants with overflow as a part of the result.

I think you could use return self.drop(first: prefix.count) which should do the same internally though.

Also I don’t remember exactly how String.Index works internally, just that it changed around Swift 3, but I think you can use another String's index if it’s matching now? So you should be able to do return self[prefix.endIndex...], or at most convert prefix.endIndex directly.

This assuming that you need unicode-correct parsing, because if you know you work with a subset of characters working on utf8/16 views will probably be much faster.

Yep, there are a few ways to solve the problem, and I would like it to be unicode-correct. I’m just hoping to not have to redo an expensive unicode comparison operation that has to have been done to check the prefix of the string.

/cc @Ben_Cohen and @Michael_Ilseman