Currently I use this workaround to pass a list of enum cases to a ChoiceOf
.
enum Fruit: String, CaseIterable {
case apple = "Apple"
case banana = "Banana"
case strawberry = "Strawberry"
}
let regex = Regex {
ChoiceOf {
try! Regex(Fruit.allCases.map(\.rawValue).joined(separator: "|"))
}
}
Is there a more elegant way to do this, without using a hardcoded regex pattern? Something like ChoiceOf(Fruit.allCases)
?
This is kind of a hack too, but you can see how the regex builders work in the Swift evolution proposal:
becomes
Rather than
RegexComponentBuilder
, we can useAlternationBuilder
here to make aChoiceOf
. You can see that the way thatbuildExpression
andbuildPartialBlock
are called are like amap
andreduce
.We can put this into an extension:
Notably, this does not work when the array is empty, i.e. when there is no choice to be made. You cannot just return:
Choice { }
. That violates one of the constraints of that initialiser. And indeed,Choice { }
doesn't make sense anyway.I think this is also why this isn't supported out of the box - the compiler cannot determine whether
Fruits.allCases
, or whatever other array you give it, is empty or not.