Uploaded image for project: 'Swift'
  1. Swift
  2. SR-13188

Please support @ViewBuilder for properties

    XMLWordPrintable

    Details

      Description

      I would like you consider adding support for @ViewBuilder to be used with properties, so that the memberwise initializer Swift generates for structs automatically gains that function builder.

      As an example, if I wanted to implement a custom SwiftUI VStack right now, I might start with this:

      struct CustomVStack<Content: View>: View {
          let content: () -> Content
      
          var body: some View {
              VStack {
                  // custom stuff here
                  content()
              }
          }
      }
      

      However, that doesn't support @ViewBuilder, and so this kind of code would not work:

      CustomVStack {
          Text("Hello")
          Text("Hello")
      }
      

      To fix this, I need to define a custom initializer:

      init(@ViewBuilder content: @escaping () -> Content) {
          self.content = content
      }
      

      In this simple example it isn't a massive problem, but often that initializer has to copy in lots of values – it does exactly what the memberwise initializer did now just with @ViewBuilder for the single content property.

      Ideally I'd like to be able to write something along these lines:

      struct CustomVStack<Content: View>: View {
          @ViewBuilder let content: () -> Content
      
          var body: some View {
              VStack {
                  // do stuff
                  content()
              }
          }
      }
      

      Thank you!

        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            twostraws Paul Hudson
            Votes:
            1 Vote for this issue
            Watchers:
            5 Start watching this issue

              Dates

              Created:
              Updated:
              Resolved: