【问题标题】:Swift Playground with async/await "cannot find 'async' in scope"带有 async/await 的 Swift Playground “在范围内找不到‘async’”
【发布时间】:2021-09-01 09:10:50
【问题描述】:

我正在尝试在 Xcode Playground 上运行这个异步函数:

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
}
    
let result = try! await getJson()
print(result)

我收到此错误消息:

error: ForecastPlayground.playground:27:25: error: 'async' call in a function that does not support concurrency
let result = try! await getJson()
                        ^

所以我尝试在我的 func 调用中创建 am async 块:

async{
    let result = try! await getJson()
    print(result)
}

然后我收到了这个错误信息:

Playground execution failed:

error: ForecastPlayground.playground:27:1: error: cannot find 'async' in scope
async{
^~~~~

我尝试使用新的 @MainActor 属性注释我的函数,但它不起作用。

我做错了什么?

【问题讨论】:

    标签: swift async-await swift-playground xcode13 swift5.5


    【解决方案1】:

    对于 Xcode 13,要在 Playground 中使用 asyncawait,只需导入 Foundation 并将代码包装在一个分离的任务中。

    import Foundation
    
    Task.detached {
        func borat() async -> String {
            await Task.sleep(1_000_000_000)
            return "great success"
        }
    
        await print(borat())
    }
    

    这是因为您的代码只有 3 个地方可以调用异步函数: (1) 在异步函数或属性的主体中; (2) 在标记为@main 的类、结构或枚举的静态main() 方法中; (3) 在一个分离的子任务中。

    【讨论】:

      【解决方案2】:

      将导入添加到_Concurrency(下划线,因为这仍然是一个测试版功能)或使用它的库,例如UIKitSwiftUI。 不过,Swift Playgrounds 目前似乎无法访问所有并发功能,例如 async let

      总结

      import _Concurrency
      

      【讨论】:

        猜你喜欢
        • 2022-01-10
        • 2018-10-29
        • 2019-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多