为什么在尝试使用控制流时SwiftUI会引发错误? [英] Why does SwiftUI throw errors when I try to use control flow?

查看:457
本文介绍了为什么在尝试使用控制流时SwiftUI会引发错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SwiftUI为什么喜欢抛出类似错误

Why does SwiftUI like to throw errors like

包含控制流语句的封闭不能与函数构建器"ViewBuilder"一起使用

Closure containing control flow statement cannot be used with function builder 'ViewBuilder'

当我只是尝试类似的东西

When I simply try something like

VStack {
    for i in 0...10 {
        Text("Hello, world!")
    }
}

它不会编译.为什么要迅速护理? SwiftUI框架甚至如何检测是否存在控制流语句并引发错误?

It will not compile. Why does swift care? How does the SwiftUI framework even detect if there are control flow statements, and throw errors?

推荐答案

SwiftUI框架如何甚至检测是否存在控制流语句并引发错误?

How does the SwiftUI framework even detect if there are control flow statements, and throw errors?

不是. Swift 语言(即编译器)可以检测到这一点.这不是抛出错误",而是说您的代码在语法上无效,因此无法对其进行编译.

It doesn't. The Swift language (i.e. the compiler) detects this. It is not "throwing an error", it is just saying your code is not syntactically valid so it can't compile it.

要了解原因,请问自己语法是什么

To see why, ask yourself what is the syntax

VStack {
    // ...
}

它是VStack结构的初始化程序,由函数生成器介导,从根本上改变了Swift语法的工作方式,将其转变为特定领域的语言.您正在调用此方法:

It is the initializer for a VStack struct, mediated by a function builder, which basically changes the way Swift syntax works, turning it into a domain-specific language. You are calling this method:

https://developer.apple.com/documentation/swiftui/vstack /3278367-init

花括号中的东西是最后一个参数:

The thing in curly braces is the last parameter:

@ViewBuilder content: () -> Content

因此,这是函数的函数体,必须返回Content(一种View).由于函数构建器的工作方式,您唯一可以做的就是返回一个View;或者,感谢函数构建器,您可以说出一系列View对象,它们将为您组合并返回.在这种情况下,就是 all .

So this is a function body for a function that must return a Content, which is a kind of View. Because of the way the function builder works, the only thing you are allowed to do here is return a View — or, thanks to the function builder, you can say a sequence of View objects and they are combined for you and returned. And that is all you are allowed to do in this context.

您的用例正是 ForEach 结构:这样,您就可以在函数构建器的域内循环生成View对象.

Your use case is exactly why a ForEach struct is provided: it's so that you have a way to produce your View objects in a loop within the function builder's domain.

这篇关于为什么在尝试使用控制流时SwiftUI会引发错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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