Skip to content

Instantly share code, notes, and snippets.

@iandundas
Last active July 22, 2025 09:20
Show Gist options
  • Save iandundas/a2a4b8082f645f67d160e96df5ca4de6 to your computer and use it in GitHub Desktop.
Save iandundas/a2a4b8082f645f67d160e96df5ca4de6 to your computer and use it in GitHub Desktop.
Eventually a EXC_BAD_ACCESS
/*
Eventually throws a EXC_BAD_ACCESS, reliably around iteration 130688, I think due to stack overflow.
https://share.cleanshot.com/qQdj9ygc
*/
import SwiftUI
@Observable
class MyObservableCounter {
var value = 0
func start() {
value += 1
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
self.start()
}
}
}
class Owner {
let counter = MyObservableCounter()
func setup() {
withObservationTracking(of: self.counter.value) { value in
print("Counter changed to \(value)")
}
counter.start()
}
}
struct ContentView: View {
@State var owner = Owner()
var body: some View {
VStack {
Text("Hello")
}
.onAppear {
owner.setup()
}
}
}
// https://www.polpiella.dev/observable-outside-of-a-view
public func withObservationTracking<T>(of value: @escaping @autoclosure () -> T, execute: @escaping (T) -> Void) {
Observation.withObservationTracking {
execute(value())
} onChange: {
RunLoop.current.perform {
withObservationTracking(of: value(), execute: execute)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment