Swift 5.4 supports writing @ViewBuilder attribute to stored properties
Prior to Swift 5.4, if I wanted to implement a custom SwiftUI VStack, I have to write like this
struct CustomStackView<Content: View >: View {
let content: () -> Content
var body: some View {
VStack {
content()
}
}
}
And used like this
CustomStackView<Text> {
Text("Hello world")
}
It looks fine, but if you notice that CustomStackView
doesn't support @ViewBuilder
so we can't write DSL syntax like HStack, VStack
VStack {
Text("Hello world")
}
so we end up writing our custom initializer in the CustomStackView
and marking our content with @ViewBuilder
.
struct CustomStackView<Content: View >: View {
let content: () -> Content
init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}
var body: some View {
VStack {
content()
}
}
}
And use like this
CustomStackView {
Text("Hello world")
}
Now, Swift 5.4, we don't need to write a custom initializer. We can directly mark property with @ViewBuilder
, which helps the compiler implicitly generate the memberwise initializer.
//Swift 5.4
struct CustomStackView<Content: View >: View {
@ViewBuilder let content: () -> Content
var body: some View {
VStack {
content()
}
}
}
Thanks for the reading.