You need to enable JavaScript to run this app. Xcode Playground使用async/await提示cannot find 'async' in scope如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Xcode Playground使用async/await提示cannot find 'async' in scope如何解决

问题原因及解决方案

错误1:'async' call in a function that does not support concurrency

出现该报错的原因是Xcode Playground的顶层执行环境是同步上下文,不支持直接执行await异步调用,必须将异步代码放到并发任务上下文中才能执行。

错误2:cannot find 'async' in scope

Swift 并发模型正式版废弃了测试阶段的async { }创建异步任务的语法,目前创建异步任务统一使用Task { }写法,因此编译器无法识别async符号。
给函数添加@MainActor标记无法解决问题的原因是,该标记仅限定函数的执行队列,不会自动为顶层调用创建异步执行上下文。

正确修改方案

将异步调用部分替换为Task块包裹即可,完整可运行代码如下:

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

enum NetworkingError: Error {
    case invalidServerResponse
    case invalidCharacterSet
}

func getJson() async throws -> String {
        let url = URL(string:"https://jsonplaceholder.typicode.com/todos/1")!
        let (data, response) = try await URLSession.shared.data(from: url)
        
        guard let httpResponse = response as? HTTPURLResponse,
              httpResponse.statusCode == 200 else {
                  throw NetworkingError.invalidServerResponse
              }
        
        guard let result = String(data: data, encoding: .utf8) else {
            throw NetworkingError.invalidCharacterSet
        }
        
        return result
}

// 替换为Task块创建异步任务
Task {
    let result = try! await getJson()
    print(result)
}

内容的提问来源于stack exchange,提问作者Sebastian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 04:06:11