# Runtime crash when using Reference for optional output

**URL:** <https://forums.swift.org/t/runtime-crash-when-using-reference-for-optional-output/73255>\
**Category:** Using Swift\
**Tags:** regex\
**Created:** [July 18, 2024, 9:57am UTC](https://forums.swift.org/t/runtime-crash-when-using-reference-for-optional-output/73255 "2024-07-18T09:57:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Skoti](https://avatars.discourse-cdn.com/v4/letter/s/71e660/32.png) [@Skoti](https://forums.swift.org/u/Skoti)\
**Post date:** [July 18, 2024, 9:57am UTC](https://forums.swift.org/t/runtime-crash-when-using-reference-for-optional-output/73255/1 "2024-07-18T09:57:14Z")

</div>

```swift
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:

```swift
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:

```swift
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!

```swift
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>`

---

<div class="post-metadata">

**Author:** ![robinkunde](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/robinkunde/32/12948_2.png) [@robinkunde](https://forums.swift.org/u/robinkunde)\
**Post date:** [April 30, 2025, 4:08pm UTC](https://forums.swift.org/t/runtime-crash-when-using-reference-for-optional-output/73255/2 "2025-04-30T16:08:29Z")

</div>

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

In your example, the type of `regex` is:

```swift
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.

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

```
