Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'async' call in a function that does not support concurrency swift ios Xcode async/await

I'm trying to use async/await with Swift 5.5. I have my async function, but whenever I try to call it, I get this error:

'async' call in a function that does not support concurrency

Here's the code sample:

class TryThis {
    func getSomethingLater(_ number: Double) async -> String {
        // test - sleep for 3 seconds, then return
        Thread.sleep(forTimeInterval: 3)
        return String(format: ">>>%8.2f<<<", number)
    }
}

let tryThis = TryThis()

let result = await tryThis.getSomethingLater(3.141592653589793238462)
print("result: \(result)")

What's the solution for this??

like image 770
drewster Avatar asked Jun 10 '21 16:06

drewster


2 Answers

The answer here is that the "await getSomethingLater" must be called from an async context. Literally that means changing this:

let result = await tryThis.getSomethingLater(3.141592653589793238462)
print("result: \(result)")

into this:

Task {
    let result = await tryThis.getSomethingLater(3.141592653589793238462)
    print("result: \(result)")
}

So the whole thing becomes:

class TryThis {
    func getSomethingLater(_ number: Double) async -> String {
        // test - sleep for 3 seconds, then return
        Thread.sleep(forTimeInterval: 3)
        return String(format: ">>>%8.2f<<<", number)
    }
}

let tryThis = TryThis()

Task {
    let result = await tryThis.getSomethingLater(3.141592653589793238462)
    print("result: \(result)")
}

Here's the output:

result: >>> 3.14<<<

There's great info in the Meet sync/await in Swift video from WWDC21.

like image 108
drewster Avatar answered Sep 19 '22 18:09

drewster


When calling async code (including actor fields) from non-async code, you have to wrap it in a Task:

Task {
    let result = await tryThis.getSomethingLater(3.141592653589793238462)
    print("result: \(result)")
}

Further reading: Concurrency — The Swift Programming Language (Swift 5.5)

like image 29
Ky. Avatar answered Sep 17 '22 18:09

Ky.