Function Builder not working when only one value?

﹥>﹥吖頭↗ 提交于 2019-12-22 11:35:43

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/58409839/function-builder-not-working-when-only-one-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!