How to pass Regex object for use inside SwiftUI View

I am trying to make a textfield that can do its own validation for input using the new Regex APIs. For example, if I pass in the email regex, it can have a green border when its a valid email and red border otherwise. So far I have this:

struct MyTextField: View {

    private var placeholder: String
    @Binding private var text: String
    private var regex: (any RegexComponent)?

    var body: some View {
        TextField(placeholder, text: $text)
        .onChange(of: $text) { newValue in
            guard let regex = regex else {
                return
            }
            if text.matches(of: regex).isEmpty {
                // show invalid state
            } else {
                // show valid state
            }
    }
}

However I get Command SwiftCompile failed with a nonzero exit code due to a type checking error. What is the correct type to use here?

Where does it crash, precisely ?

Could this help ? https://hasancanakgunduz.medium.com/swift-5-7-regex-and-regexbuilder-f658f0f1aade

So I changed the type to Regex but I still get this error when trying to use my View:

MyTextField(placeholder: "Phone Number", text: $phone, validation: /(0-9)*.{10}/)

produces the error: Cannot convert value of type 'Regex<(Substring, Substring?)>' to expected argument type 'Regex'

But then I did a simple test in a playground:

let sub: Substring = "sub"

let string: Substring? = "string"

let substring = (sub, string)

if let thing = substring as? Any {
    print("WE HAVE THING: \(thing)")
}

Which warns me that Conditional cast from '(Substring, Substring?)' to 'Any' always succeeds

So I'm a little confused how in the first example Regex<(Substring, Substring?)> can't be cast to Regex but (Substring, Substring?) can cast to Any in this example.

How to pass Regex object for use inside SwiftUI View
 
 
Q