How to reuse views using @ViewBuilder - SwiftUI

Dec 17, 2021 1 min read
How to reuse views using @ViewBuilder - SwiftUI

The body property of any SwiftUI automatically gets the ability to return different views thanks to a special attributed called @ViewBuilder. This is implemented using Swift’s result builder system, and it understands how to present two different views depending on our app’s state. Examples:

Reusable view without arguments

struct ContentView: View {
    @ViewBuilder var tossResult: some View {
        if Bool.random() {
        } else {
            Text("Better luck next time")

    var body: some View {
        VStack {
            Text("Coin Flip")

                .frame(width: 400, height: 300)                

Reusable view with arguments

Here we are taking a String from another view and using it here.
Usage on other views: CoinRowView(for: "Title")

func CoinRowView(for coin: String) -> some View {
    ZStack {
Great! Next, complete checkout for full access to ArturoFM.
Welcome back! You've successfully signed in.
You've successfully subscribed to ArturoFM.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.