Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: deinit equivalent?

Tags:

swiftui

What is the equivalent of UIKit View's deinit for a SwiftUI view?

I have looked at .onDisappear... but, it does not seem to me that is the hook I should be using to know when a SwiftUI View is gone for good, for example during navigation etc...

like image 301
zumzum Avatar asked Apr 09 '26 22:04

zumzum


1 Answers

There is no deinit for structs, however, you can use some of the workarounds:

  1. If you have an instance wrapped with the property wrapper @StateObject, you can use deinit of the class, e.g.:
struct YourView: View {
  @StateObject var viewModel = ViewModel()
}

class ViewModel: ObservableObject {
  init() {}
  deinit { /* When the view is destroyed 
  the initialized ViewModel will be deinited as well */ }
}
  1. Use the code that is supposed to be in deinit right before dismiss():
struct SheetContents: View {
    @Environment(\.dismiss) private var dismiss
    var body: some View {
        Button("Done") {
            /* "Deinit" code here. */
            dismiss()
        }
    }
}
like image 159
nevinchanyi Avatar answered Apr 16 '26 06:04

nevinchanyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!