我正在尝试在 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 属性注释我的函数,但它不起作用。
我做错了什么?