Skip to content

Trying to run async code doesn't work #101

Answered by kishikawakatsumi
alobaili asked this question in Q&A
Discussion options

You must be logged in to vote

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.

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 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…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@alobaili
Comment options

Answer selected by kishikawakatsumi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants