Seb*_*ian 5 async-await swift swift-playground swift5 xcode13
我正在尝试在 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)
Run Code Online (Sandbox Code Playgroud)
我收到此错误消息:
error: ForecastPlayground.playground:27:25: error: 'async' call in a function that does not support concurrency
let result = try! await getJson()
^
Run Code Online (Sandbox Code Playgroud)
所以我尝试在我的 func 调用中创建 async 块:
async{
let result = try! await getJson()
print(result)
}
Run Code Online (Sandbox Code Playgroud)
然后我收到了这个错误消息:
Playground execution failed:
error: ForecastPlayground.playground:27:1: error: cannot find 'async' in scope
async{
^~~~~
Run Code Online (Sandbox Code Playgroud)
我尝试使用新的 @MainActor 属性注释我的函数,但它不起作用。
我做错了什么?
添加导入_Concurrency(下划线,因为默认情况下应该包含它)或使用该库的库,例如UIKit或SwiftUI。不过,Swift Playgrounds 目前似乎无法访问所有并发功能,例如async let.
总之
import _Concurrency
Run Code Online (Sandbox Code Playgroud)