Have a way to force SwiftUI View must implement/call a function in lifecycle example appear, disappear

In SwiftUI, some solutions for a View must implement a ViewModifier or Protocol in LifeCyrcle. But in the View structure, it should be missing if another developer code forgot to be called. I want to implement it as a protocol; another developer must be called for that function in View LifeCycle. Have some solution to that?

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
            .padding()
           .onAppear {
              // doSomething()
          }
          .mustCall { // Foo() } // I want it must be call.
    }
}
struct MustImplement: ViewModifier {
    var doSomething: () -> Void

    func body(content: Content) -> some View {
        ZStack(alignment: .bottomTrailing) {
            content
               .onAppear {
                   // doSomething()
               }
        }
    }
}

extension View {
    func mustCall(onCall: () -> Void) -> some View {
        modifier(MustImplement(doSomething: onCall)
    }
}

Hi, Tài Lê, welcome to the Swift forums!

I don't know the answer to your question, but I think you may have better success asking over at Apple's Developer Forums, since your question is about SwiftUI, which is an Apple framework.

This forum, and the "Evolution" category in particular, is about Swift the language and its development.

Discussion about how to use specific frameworks, even those made by Apple, are off-topic on this forum.

Hope, you'll get the answers you're looking for, and if you want to contribute to discussion about the language as such, you're welcome to stick around :smile:

1 Like

Yes. It's my mistake when ask a question with none target of our forum. Thank for suggestion.