Creating async/await functions in a Swift Playground
Swift Playgrounds in Xcode are super useful for trying out Swift syntax either for learning, or for refining code before incorporating it into a real project. By default async
functions can't be executed in a playground, but it is possible. Here's an example:
import Foundation
import _Concurrency
import PlaygroundSupport
var success: Bool
func add(_ a: Int, _ b: Int) async -> Int {
try? await Task.sleep(for: .seconds(5))
return a + b
}
Task {
let c = await add(5, 4)
print("\(c)") // 9
PlaygroundPage.current.finishExecution()
}
PlaygroundPage.current.needsIndefiniteExecution = true