Runtime crash when using Reference for optional output

let capitals: CharacterClass = "A"..."Z"
let delimiters: CharacterClass = .anyOf("_")
let reference = Reference<Substring>()
let regex = Regex {
    ChoiceOf {
        Capture(as: reference) {
            OneOrMore(delimiters)
        }
        OneOrMore(capitals)
    }
}
"AbCdE_f_G__h".matches(of: regex).forEach { match in
    print(match.output)
    print(match[reference])
}

This should be a type-safe way to obtain the optional value for the reference, but it crashes in runtime with:

Could not cast value of type 'Swift.Optional<Swift.Substring>' (0x1ec721a10) to 'Swift.Substring' (0x1f0401450).

If I change the reference to let reference = Reference<Substring?>()
it ends with a compile-time error:

Initializer 'init(as:_:)' requires the types 'Substring?' and 'Regex<OneOrMore<Substring>.RegexOutput>.RegexOutput' (aka 'Substring') be equivalent

Shouldn't the compile require such captures to use an optional type?
Otherwise, the compile-time type-safety is compromised.
Is there a way to make it work with RegexBuilder?

I can easily make it work the usual way and still type-safe!

let regex = try! Regex("[A-Z]+|(?<delimiters>[_]+)", as: (Substring, delimiters: Substring?).self)
"AbCdE_f_G__h".matches(of: regex).forEach { match in
    print(type(of: match.output.delimiters))
    print(match.output.delimiters)
}

where match.output.delimiters is Optional<Substring>

I came across the same issue today where the Capture was inside an Optionally.

In your example, the type of regex is:

Regex<Regex<ChoiceOf<(Substring, Substring?)>.RegexOutput>.RegexOutput>

So clearly, once the entire builder expression is evaluated, the compiler knows that the result of the capture is going to be optional. But it doesn't have a way to now require the reference's type to be optional, because when it evaluates each Capture expression, the context determines whether the capture group's output is optional or not.
I think I would have preferred it if accessing a capture group by reference always returned an optional, rather that being able to accidentally crash at runtime.

There is one workaround though, where you use TryCapture instead.

let reference = Reference<Substring?>()
let regex = Regex {
    ChoiceOf {
        TryCapture(as: reference) {
            OneOrMore(delimiters)
        } transform: { $0 }
        OneOrMore(capitals)
    }
}