I have a generic view with an optional @ViewBuilder.
I want to have two initializers, one is responsible for setting the @ViewBuilder and another which should serve as an empty default.
struct OptionalViewBuilder<Content: View>: View {
let content: (() -> Content)?
init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}
init() {
self.content = nil
}
var body: some View {
VStack {
Text("Headline")
Divider()
content?()
}
}
}
If I initialize the view with the ViewBuilder parameter, it works of course. However, when I use the empty initializer, I get the error message:
Generic parameter 'Content' could not be inferred
struct ContentView: View {
var body: some View {
OptionalViewBuilder {
Text("Text1")
Text("Text2")
}
OptionalViewBuilder() // <-- Generic parameter 'Content' could not be inferred
}
}
I know that Swift needs explicit types at runtime, but is there a way to make the default initializer work anyway?