Why does SwiftUI throw errors when I try to use control flow?

醉酒当歌 提交于 2021-02-11 13:27:15

问题


Why does SwiftUI like to throw errors like

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!")
    }
}

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


回答1:


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

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 {
    // ...
}

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

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.

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.




回答2:


You can't do that inside ViewBuilder, but you can do this instead:

VStack {
    ForEach (0..<10) {_ in
       Text("hello world")
   }
}

If you are dealing with arrays, you can use a variable instead of an underscore.

VStack {
    ForEach (0..<10) {i in
       Text("\(array[i])")
   }
}


来源:https://stackoverflow.com/questions/59970268/why-does-swiftui-throw-errors-when-i-try-to-use-control-flow

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