Search code examples
asynchronousswiftuitask

Task.detached crashing on init


This empty app is crashing on load. I'm trying to execute a function on app load asynchronously, but it keeps crashing. I'm running macOS v11 (Big Sur) and Xcode 13 with Swift 5.5 and can't find what's wrong with it.

import SwiftUI

@main
struct TestApp: App {

    init() {
        Controller.shared.load()
    }

    var body: some Scene {
        WindowGroup {
            VStack {
                Text("Hello")
            }
        }
    }
}

class Controller: ObservableObject {

    static let shared = Controller()

    @Published public var loaded = false
    @Published public var processing = false

    func load() {
        Task.detached {
            print("Hello")
        }
    }
}

Edit:

It compiles and runs but immediately crashes. There is no error message, it just crashes with

Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)

on Controller.shared.load(). If you comment out the Task.detached block it runs normally, but of course it doesn't start loading the object in the background which is what I'm actually trying to do.


Solution

  • Answering my own question, it seemed to be somehow a bug related to the versions of Xcode 13.2.1 and macOS 11.7. If the project uses 11.7 as 'Deployment Target' I would get a crash, but if I change it to 11.6 it would work correctly. Go figure.