How to call async func from sync func in Swift 5.5?

I don't understand how to call async fetch() for iOS below 15 for code below.

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, world!")
                .onTapGesture(perform: onTap)
        }
    }

    func onTap() {
        if #available(iOS 15.0, *) {
            async {
                await fetch()
            }
        } else {
            /// How to call fetch()?
        }
    }

    func fetch() async {
        Thread.sleep(forTimeInterval: 10)
    }
}

You can't use any Concurrency features on a runtime that does not support it (Swift <5.5). You'll have to create a callback-based function for the older runtime, then create a shim for the async version to maximise code reuse.

    func onTap() {
        if #available(iOS 15.0, *) {
            async {
                await fetch()
                print("done!")
            }
        } else {
            fetch {
                print("done!")
            }
        }
    }

    func fetch(complete: @escaping () -> Void) {
        DispatchQueue.global().async {
            Thread.sleep(forTimeInterval: 10)
            complete()
        }
    }

    @available(iOS 15.0, *)
    func fetch() async {
        await withCheckedContinuation { cont in 
             fetch {
                 cont.resume()
             }
        }
    }

Can you put a proof link about this restriction for iOS 15 below?

Terms of Service

Privacy Policy

Cookie Policy