bibin-jaimon / InterviewKit-iOS

5 stars 0 forks source link

How to create an optional @ViewBuilder closure in SwiftUI #31

Open bibin-jaimon opened 3 weeks ago

bibin-jaimon commented 3 weeks ago
struct DefaultView<Content>: View where Content: View {
    var customFallback: () ->  Content? = { nil }
    let title: String
    init(
        title: String,
        @ViewBuilder customFallback: @escaping () -> Content
    ) {
        self.title = title
        self.customFallback = customFallback
    }

    init(title: String) where Content == EmptyView {
        self.title = title
    }

    var body: some View {
        Text(title)
        if let customFallback = customFallback() {
            customFallback
        }
    }
}

#Preview {
    DefaultView(title: "Title")
}

#Preview {
    DefaultView(title: "Title", customFallback: { Text("Fall") })
}