在Swift中,如果在同步函数中使用 await(或调用async方法):
// 同步函数
private func runProcess() -> Bool {
let result = await withCheckedContinuation { cont in // 使用 await
因为函数本身没有被声明为async,编译器就会发生报错。
'async' call in a function that does not support concurrency
解决方案:
1、使用Task创建一个异步任务:
// 同步函数
private func runProcess() -> Bool {
// 创建异步任务,Task内可以访问异步函数
Task {
let result = await withCheckedContinuation { cont in // 使用 await
}
}
2、函数声明为async,改为异步函数:
// 异步函数
private func runProcess() async -> Bool async {
当调用该函数时,使用Task:
Task {
let value = await runProcess()
}
