Skip to main content
3 of 9
a clarification
Milos
  • 619
  • 5
  • 18

The proposed approach hangs on iOS, though not on macOS, which is fascinating in its own right. See inline comments:

@main
struct BlockerApp: App {
    
    @State var count = 0
    
    var body: some Scene {
        WindowGroup {
            VStack {
                
                Text("\(count)")
                
                Button("Increment") { // tapping on the button hangs the app
                    count += blocking { 1 } // the closure is never called
                }
            }
        }
    }
}

func blocking<A>(_ ƒ: @escaping () async -> A) -> A {
    let semafore = DispatchSemaphore(value: 0)
    let got = Got<A>()
    Task.detached(priority: .high) {
        got.a = await ƒ() // gets as far as this line but ƒ is never called
        semafore.signal()
    }
    semafore.wait()
    return got.a!
}

private class Got<A> {
    var a: A?
}
Milos
  • 619
  • 5
  • 18