Skip to content

Instantly share code, notes, and snippets.

@lzell
Created January 7, 2024 19:29
Show Gist options
  • Save lzell/6402da9692073934fc4f243291183ac2 to your computer and use it in GitHub Desktop.
Save lzell/6402da9692073934fc4f243291183ac2 to your computer and use it in GitHub Desktop.
Inspecting if dependency on Observable leaks in SwiftUI

Contents of MyApp.swift

import SwiftUI

@main
struct AnimateOnObservedPropertyChangeApp: App {
    @State var trigger = false

    var body: some Scene {
        WindowGroup {
            ZStack {
                ContentView()

                Button("Re-init Content View") {
                    self.trigger.toggle()
                }.onChange(of: self.trigger) { _, _ in }
            }
        }
    }
}

Contents of ContentView.swift

import SwiftUI

@Observable
final class DoesThisLeak {
    init() {
        print("In initializer of DoesThisLeak")
    }

    deinit {
        print("In deinitializer of DoesThisLeak")
    }
}

struct ContentView: View {
    init() {
        print("In the initializer of ContentView")
    }

    let myData = DoesThisLeak()

    var body: some View {
        Color.gray
    }
}

Output at runtime when tapping the 're-init' button:

:: startup
In initializer of DoesThisLeak
In the initializer of ContentView

:: tap on 're-init'
In initializer of DoesThisLeak
In the initializer of ContentView
In deinitializer of DoesThisLeak

:: tap on 're-init'
In initializer of DoesThisLeak
In the initializer of ContentView
In deinitializer of DoesThisLeak

That is, DoesThisLeak is not leaking.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment