@ViewBuilder on property vs in init, storing closure or result value

Viewed 28

What's the difference between:

@ViewBuilder on property

struct SomeView<Content:View>: View {
    @ViewBuilder var content: () -> Content
}

In init, storing closure

struct SomeView2<Content:View>: View {
    var content: () -> Content
    
    init(@ViewBuilder content: @escaping () -> Content) {
        self.content = content
    }
}

In init, storing result value

struct SomeView3<Content:View>: View {
    var content: Content
    
    init(@ViewBuilder content: () -> Content) {
        self.content = content()
    }
}

All solutions seem to work. So why would one select one versus another?

1 Answers

Someone asked in this year's lounge and an Apple engineer recommended storing the the result value. Probably because it's more efficient to do it once.

Q: But, what’s the recommended way to use a @ViewBuilder for custom components: calling it right away in the init() and storing the view, or calling it later inside the body and storing the view builder itself?

A: We’d generally recommend resolving it right away and storing the view

https://onmyway133.com/posts/wwdc-swiftui-lounge/#use-viewbuillder

Related