The following could be an error in the compiler, but I am posting it here because someone could have an idea what the issue is or how to circumvent it:
struct X {
nonisolated(unsafe) let pattern: any RegexComponent
func f() {
let _ = "hello".contains(pattern) // OK
let _ = "hello".firstMatch(of: pattern) // Command SwiftCompile failed with a nonzero exit code
}
}
The strange thing is that "hello".contains(pattern) compiles, but "hello".firstMatch(of: pattern) does not. (Swift 6.1.2 on macOS.)
The difference is contains returns a Bool, while firstMatch returns a Regex<Output>.Match?.
This evolution proposal defines the behavior when you pass an existential to a generic function. Unfortunately, Regex<Output>.Match cannot be erased to a general upper bound, that’s why your second invocation is invalid.
I am actually trying to use the same pattern from the above struct, but with a trailing space added. If I define a pattern via
let pattern = /a/ // for example
I can do this via:
let pattern2 = Regex { pattern; " " }
Here, the pattern has type Regex<Substring> or Regex<(Substring,Substring)> or maybe Regex<(Substring?,Substring)> or whatever, so you can use it to build another regex, and I understand why this is not possible for the type any RegexComponent.
The code from the ticket description was then thought as a mean to circumvent having to build a new regex. Actually the range of the match would suffice and not the full match (I could then look for a following space)... What else could I do besides repeating the regular expression with a trailing space added?
struct X {
nonisolated(unsafe) let pattern: any RegexComponent
nonisolated(unsafe) let patternWithTrailingSpace: any RegexComponent
init(
patternMaker: () -> (pattern: any RegexComponent, patternWithTrailingSpace: any RegexComponent)
) {
(self.pattern, self.patternWithTrailingSpace) = patternMaker()
}
}
let x = X(patternMaker: {
let pattern = /e/
return (pattern: pattern, patternWithTrailingSpace: Regex { pattern; " " })
})
print("hello".contains(x.pattern)) // true
print("he llo".contains(x.patternWithTrailingSpace)) // true
...but I still wish that there would be some compiler magic to make the construction of Regex { pattern; " " }) and the application of firstMatch for any RegexComponent (or some better type) possible.