Changing a binding variable from a secondary thread

Not sure if this is a SwiftUI question or not:

struct S { var value = 0 }

func foo(_ x: Binding<S>) {
    DispatchQueue(label: "queue").asyncAfter(deadline: .now() + 1) {
        dispatchPrecondition(condition: .notOnQueue(.main))
        x.wrappedValue.value += 1
        foo(x)
    }
}

struct ContentView: View {
    @State private var x = S()

    var body: some View {
        Text(String(x.value))
            .onAppear { foo($x) }
    }
}
@main struct TheApp: App {
    var body: some Scene {
        WindowGroup { ContentView() }
    }
}

In this app is it safe to call "x.wrappedValue.value += 1" on non-main thread? The app seems to work.

Somewhat a SwiftUI question but from a pure Swift language point of view Binding isn't Sendable and therefore not safe to call from arbitrary threads.

1 Like