ios - 在不支持并发的函数中调用'async' swift ios Xcode async/await

标签 ios swift xcode macos async-await

我正在尝试将 async/await 与 Swift 5.5 一起使用。我有我的异步函数,但每当我尝试调用它时,我都会收到此错误:

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


这是代码示例:
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)")
这个有什么解决办法??

最佳答案

这里的答案是“await getSomethingLater”必须从异步上下文中调用。从字面上看,这意味着改变这一点:

let result = await tryThis.getSomethingLater(3.141592653589793238462)
print("result: \(result)")
进入这个:
Task {
    let result = await tryThis.getSomethingLater(3.141592653589793238462)
    print("result: \(result)")
}
所以整个事情变成了:
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)")
}
这是输出:

result: >>> 3.14<<<


Meet async/await in Swift 中有大量信息来自 WWDC21 的视频。

关于ios - 在不支持并发的函数中调用'async' swift ios Xcode async/await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67925525/

相关文章:

ios - 如何在编译时查看iOS版本?

iphone - iOS 是否支持 HTTP Live Streaming 之外的任何内容?

ios - 动态创建的 UIView 在碰撞后不会动画

objective-c - 具有 __attribute__((NSObject)) 的 CF 类型的强@property 不保留

ios - Swift:创建 iOS 框架并导入框架错误:Variable used within its own initial value

ios - 不再显示 ViewController

ios - Swift Firebase 下载 map 注释上的注释图像单击

ios - Swift - 获取 ipv6 链接本地地址?

xcode - 如何让Xcode识别GraphQL文件?

ios - 提交 App UIApplicationExitsOnSuspend 时出现错误 ITMS-90040