只有一个值时,函数生成器不起作用? [英] Function Builder not working when only one value?

查看:111
本文介绍了只有一个值时,函数生成器不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个functionBuilder

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
    }
}

功能

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

使用

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

但是

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

为什么b不是20?

我尝试添加其他buildBlock

I try add other buildBlock

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

但不起作用:(

有什么主意吗?

推荐答案

有什么主意吗?

Any idea?

在失败情况下发生的情况是,{ 10 }被直接视为类型为() -> Int的闭包,并且编译器似乎根本没有考虑函数生成器.产生的代码只是返回10的函数.

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.

这似乎是一个功能",其中将{ 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...

请访问feedbackassistant.apple.com并提交报告.

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

这篇关于只有一个值时,函数生成器不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆