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

在Swift5.5中使用async/await时,调用async函数的时候,出现了一个错误。

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

我的代码如下:

public func concurrentCode(n: Int) async -> Int  {
       let number = n * 2
        do {
            try await Task.sleep(nanoseconds: 2 * 1_000_000_000)
        } catch  {
            print("error:\(error)")
        }
        return number
    }
    
   let con = Concurrent()

   let number =  await con.concurrentCode(n: 10)
     print("result:\(number)")

原因是:await concurrentCode的方法必须在async函数中进行调用。即调用者必须是异步的。

将代码改成如下即可:

 Task {
        let con = Concurrent()
        let number =  await con.concurrentCode(n: 10)
        print("result:\(number)")
  }

得到输出参数是:

result:20
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容