Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swiftui

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?

like image 688
Coconuts Avatar asked Oct 21 '25 05:10

Coconuts


1 Answers

Someone asked in this year's lounge and an Apple engineer recommended storing the the result value.

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

E.g. this version

struct SomeView3<Content:View>: View {
    let content: Content
    
    init(@ViewBuilder content: () -> Content) {
        self.content = content()
    }
}
like image 136
malhal Avatar answered Oct 24 '25 10:10

malhal



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!