giik
(Giik)
1
Consider the following simple @resultBuilder adding integers:
@resultBuilder struct SumBuilder<Result: SignedInteger> {
typealias Term = Result
static func buildBlock(_ components: Term...) -> Term {
return components.reduce(0) { $0 + $1 }
}
static func buildExpression<T: SignedInteger>(_ expression: T) -> Term {
Term(expression)
}
}
With it, I can write things like:
var x1 = SumBuilder.buildBlock(2, 3, 462534252412524)
var x2: Int64 = SumBuilder.buildBlock(2, 3, 462534252412524)
but in
@SumBuilder<Int32> var y: Int32 {
10
Int32(-1)
}
the result type needs to be repeated twice—taking either Int32 out is an error. The following
@SumBuilder<Int32> var y {
...
is also an error: computed property must have an explicit type.
Is there a way around that? Or, maybe I am doing this all wrong in which case what would be better (assuming I want to have the generic builder)?
Cheers,
paiv
(🇺🇦 Pavel Ivashkov)
2
The result builder would expand like this:
var x = SumBuilder.buildExpression(2)
var y = SumBuilder.buildExpression(3)
var z = SumBuilder.buildExpression(462534252412524)
var r: Int64 = SumBuilder.buildBlock(x, y, z)
and this is where you get type mismatch.