Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI when can i use if statement in result builder?

Tags:

ios

swiftui

I notice that sometimes I am able to use if-else statement in SwiftUI's result builder just fine. For example, inside a body:

struct MyView: View {
  var body: some View {
    if foo {
      Text("foo")
    } 
  }
}

However, sometimes I can't, for example, inside view modifier:

  func body(content: Content) -> some View {
    content
      .toolbar {
        if foo { Button("foo") {} }
      }
    }
  }

This above gives me error saying:

Closure containing control flow statement cannot be used with result builder 'ToolbarContentBuilder'

This is so confusing. Why are they different? When can I use if-else, and when it should be avoided (and in that case, why is it bad? and what should I do? )

Edit:

I tried to put the button under a Group {} under the toolbar. It's not working either:

      .toolbar {
        Group {
          if true { // can't put if here
            Button("foo")

Got this error:

Closure containing control flow statement cannot be used with result builder 'CommandsBuilder'

1 Answers

ToolbarContentBuilder does not allow if statements, it's designed to use ToolbarItemGroup, where you can use if like a regular ViewBuilder:

var body: some View {
    NavigationView {
        Text("Hello, world!")
            .toolbar {
                ToolbarItemGroup(placement: .navigationBarTrailing) {
                    if foo { Button("foo") {} }
                }
            }
    }
}
like image 102
Steve M Avatar answered Oct 26 '25 05:10

Steve M



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!