I have the following function that uses Swift 5.7's Regex builder:
static func numberStartingWith6(strictLength: Bool) -> some RegexComponent {
let myRegex = Regex {
Optionally {
"6"
if strictLength {
Repeat(CharacterClass.digit, count: 9)
}
else {
Repeat(0...8) {
CharacterClass.digit
}
}
}
}
but i get the following syntax error at the Optionally type:
Type '() -> ()' cannot conform to 'RegexComponent'
I tried to figure out the underlying type of the myRegex variable in the function above and it was:
Regex<Regex<Optionally<Substring>. RegexOutput>. RegexOutput>
How to declare the correct return type in the function's signature so that I don't care about the regex builder's underlying type (i.e. type erasure).
RegexComponentBuilderdoesn't supportifstatements. There is nobuildEitherorbuildIfmethods.The error is rather confusing. Since you used an
ifstatement in the closure, the compiler no longer thinks this is a@RegexComponentBuilderclosure, and tries to match the other initialiser overloads. It found this overload that takes aRegexComponent, and says the closure (of type() -> ()) can't be converted to that.ifstatements are not supported possibly because if the branches capture different things, theOutputtype of the resulting regex is going to be very complicated.For example, if you have
Then the
Outputtype of the regex would beThe amount of
buildEitherandbuildIfoverloads needed for this is rather unmanageable.You can write a
buildEitheryourself if you only capture the same types in each branch:That said, your code does not need an if statement. Just do:
Or if the regex component in each branch is a different type, you can just declare a
let: