Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Builder not working when only one value?

Tags:

swift

swift5

I have a functionBuilder

@_functionBuilder
struct MyBuilder {
    static func buildBlock(_ numbers: Int...) -> Int {
        var result = 0
        for number in numbers {
            result += number * 2
        }
        return result
    }
}

Function

func myFunc(@MyBuilder builder: () -> Int) -> Int {
    builder()
}

use

let a = myFunc {
    10
    20
}
print(a) // print 60 is work!

but

let b = myFunc {
    10
}
print(b) // print 10?

Why is b not 20?

I try add other buildBlock

static func buildBlock(number: Int) -> Int {
    return number * 2
}

But not working :(

Any idea?

like image 883
aiur Avatar asked Jan 19 '26 04:01

aiur


1 Answers

Any idea?

What is happening in the failing case is that { 10 } is being treated as a closure of type () -> Int directly and the compiler doesn't appear to consider the function builder at all. The code that is produced is simply a function which returns 10.

This appears to a "feature" where the recognition of { 10 } as a simple closure overrides its possible recognition as a use of the function builder. This may just be a compiler issue or worse it might be a language definition problem...

Please head to feedbackassistant.apple.com and file a report.

like image 51
CRD Avatar answered Jan 21 '26 20:01

CRD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!