I'm trying to run this async function on 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)
and I'm receiving this error message:
error: ForecastPlayground.playground:27:25: error: 'async' call in a function that does not support concurrency
let result = try! await getJson()
^
So I tried to create am async block in my func call:
async{
let result = try! await getJson()
print(result)
}
And then I received this error message:
Playground execution failed:
error: ForecastPlayground.playground:27:1: error: cannot find 'async' in scope
async{
^~~~~
I tried to annotated my function with the new @MainActor attribute and it doesn't work.
What I'm doing wrong?
Add an import to _Concurrency
(underscore because this is supposed to be included by default) or a library that makes use of the library, such as UIKit
or SwiftUI
.
It appears that Swift Playgrounds don't have access to all concurrency features at the moment though, such as async let
.
In summary
import _Concurrency