Async in Playground

Can I use async in Playground? If so, please show an example.

func doStuff() async {
  print("here")
}

doStuff()
print("After")

//error: 'async' call in a function that does not support concurrency
Answered by Dirk-FU in 680221022

Like with every async function called from a synchronous context (the global context of your playground) you have to wrap your call to doStuff() in an async block and await it:

async{
     await doStuff()
}

This is expected to change to

Task.async{
    await doStuff()
}

in a later beta.

The following list of WWDC videos covering Swift concurrency should provide further background: Meet Swift Concurrency

Accepted Answer

Like with every async function called from a synchronous context (the global context of your playground) you have to wrap your call to doStuff() in an async block and await it:

async{
     await doStuff()
}

This is expected to change to

Task.async{
    await doStuff()
}

in a later beta.

The following list of WWDC videos covering Swift concurrency should provide further background: Meet Swift Concurrency

Sorry, I forgot about three additional things you have to do to use Swift concurrency in Playgrounds:

import _Concurrency
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

I'm getting this error relative to PlaygroundSupport:

Module compiled with Swift 5.3.2 cannot be imported by the Swift 5.5 compiler

I've brought the compiler in from Swift.org, and set it as the toolchain in Xcode. Any ideas how I can upgrade the module / what I've forgotten to do?

I've brought the compiler in from Swift.org, and set it as the toolchain in Xcode.

This works for general compilation but it does not work with playgrounds. If you want to… hey hey… play with Swift concurrency in a playground, do that from Xcode 13 beta. If you create an iOS playground, it’ll run in an iOS 15 beta simulator. To use a macOS playground, you’ll need to run Xcode on a macOS 12 beta.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Async in Playground
 
 
Q