Making a Call to a Distant Struct

Let me say that I have three structs that are sequentially connected.

ContentView -> FirstView -> SecondView

And I want to make a call from SecondView to ContentView with a button tap. So I have the following lines of code.

import SwiftUI

struct ContentView: View {
	@State var goToFirst = false

    var body: some View {
		NavigationStack {
			VStack {
				NavigationLink {
					FirstView(callBack: {
						sayHello()
					}, goToSecond: $goToFirst)
				} label: {
					Text("Go to First")
				}
			}
		}
		.navigationDestination(isPresented: $goToFirst) {

		}
    }

	func sayHello() {
		print("Hello!")
	}
}

struct FirstView: View {
	@State var callBack: (() -> Void)?
	@Binding var goToSecond: Bool

	var body: some View {
		VStack {
			Button("Go to Second") {
				goToSecond.toggle()
			}
		}
		.navigationDestination(isPresented: $goToSecond) {
			SecondView(callBack: callBack)
		}
	}
}

struct SecondView: View {
	@State var callBack: (() -> Void)?

	var body: some View {
		VStack {
			Button("Tap me to make a call to ContentView") {
				callBack?()
			}
		}
	}
}

If I tap the button in SecondView, my ContentView will receive a call and call the sayHello function. Since ContentView and SecondView are not directly connected with each other, they have to through FirstView in this case. I wonder if there's a better or easier approach in having SecondView make a call to ContentView? In UIKit and Cocoa, you can make a delegate call to a distant class even when two classes are not directly connected with other. Using the notification is another option. In SwiftUI, I suppose you don't use either of them. Muchos thankos.

Replies

I think another approach is use of an ObservableObject class with

onReceive(_:perform:)

.