UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

[Solved: pilot error] Can compile with @StateObject, but it doesn't work at runtime

Forums > SwiftUI

Per @Hatsushira's suggesstion, I moved the init of both objects into my initializer. Compiles fine, but now I can't get any notifications. I've tried various different permutations, most of which don't compile, some of which compile but then complain at runtime about the object being referenced while not being installed on a view--another error message I can barely grasp. Welcoming any suggestions, cheers.

struct ArkansasApp: App {
    @StateObject var appState: AppState
    @StateObject var arkansasScene: ArkansasScene

    init() {
        let state = AppState()
        let scene = ArkansasScene(appState: state)

        _appState = StateObject(wrappedValue: state)
        _arkansasScene = StateObject(wrappedValue: scene)

    var body: some Scene {
        WindowGroup {

class AppState: ObservableObject {
    @Published var numberOfStopSignsInArkansas = 400000

class ArkansasScene: SKScene, SKSceneDelegate, ObservableObject {
    @ObservedObject var appState: AppState

    var stopSignObserver: AnyCancellable!

    let side: Double = 1024

    init(appState: AppState) {
        self._appState = ObservedObject(initialValue: appState)

        super.init(size: CGSize(width: side, height: side))


    func ping() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            [weak self] in guard let myself = self else { return }
            myself.appState.numberOfStopSignsInArkansas += 1
            print("new value \(myself.appState.numberOfStopSignsInArkansas)")

    override func didMove(to view: SKView) {
        stopSignObserver = appState.$numberOfStopSignsInArkansas.sink {
            print("Got notification \($0)")

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")

I didn't instantiate the view that contains ArkansasScene 🤦‍♂️


Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.