Given a variadic type with a minimum of two elements, is it possible to create an instance of such type with a result builder?
I have defined a ChoiceOf
type (very similar to the one defined in the RegexBuilder
module), which enforces the existence of two elements, but it lets you write more.
struct ChoiceOf<N1, N2, each N> {
let nodes: Nodes
private init(nodes first: N1, _ second: N2, _ rest: repeat each N) {
self.nodes = (first, second, repeat each rest)
}
typealias Nodes = (N1, N2, repeat each N)
}
I would like to define ChoiceOf
instance with result builders (again very similar to RegexBuilder
). But I would like the compiler to complain if only a single element is defined.
let component = ChoiceOf {
"Hello"
} // 🔥 Error
let component = ChoiceOf {
"Hello"
"Goodbye"
7
} // ✅ Success
The initializer is easy to write, but I cannot think of a way to declare the result builder. Any ideas?
extension ChoiceOf {
init(@ChoiceBuilder builder: () -> Self) {
self = builder()
}
}
@resultBuilder enum ChoiceBuilder {
typealias Intermediate = ...
static func buildExpression<T>(_ expression: T) -> Intermediate { ... }
static func buildPartialBlock(first: Component) -> Intermediate { first }
static func buildPartialBlock(accumulated: Intermediate, next: Intermediate) -> Intermediate { ... }
static func buildFinalResult(_ component: Intermediate) -> ChoiceOf<...> { ... }
}