Trying to run async code doesn't work #101
-
I'm trying to start execution on an async context to support running async code like so: @main
struct Main {
static func main() async {
await doSomething()
}
static func doSomething() async {}
} but I get the following error on
I'm guessing there's some kind of import on Is there a way around this to make experimenting with async code easy? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You're right. Swiftfiddle automatically add the code equivalent to @main in favor of simplicity. import Foundation
struct Main {
static func main() async {
await doSomething()
}
static func doSomething() async {
print("doSomething")
}
}
Task.detached {
await Main.main()
exit(EXIT_SUCCESS)
}
RunLoop.main.run() https://swiftfiddle.com/4e3ig5vph5d2vnl2biuhoj33ti There are two important points. The execution of the async method will return soon, so use RunLoop to wait for avoiding the whole execution finishes before await function finishes. The following is a sample of Async/Await that I wrote. Please use this as a reference. |
Beta Was this translation helpful? Give feedback.
You're right. Swiftfiddle automatically add the code equivalent to @main in favor of simplicity.
Also Async/await is still actively changed and Linux support is behind that of macOS. so the following is a bit old, but it works.
https://swiftfiddle.com/4e3ig5vph5d2vnl2biuhoj33ti
There are two important points.
The Swiftfiddle code is executed at the top level, so executing async function, you need to enclose it in
Task.detached()
.The execution of the asyn…