Search code examples
iosasynchronousasync-awaitswift-playground

async await unexpected error in playground


I have this code in playground for iOS, XCode v15.3:

import Foundation
import PlaygroundSupport

func fetchWeatherHistory() async -> [Double] {
    (1...100).map { _ in Double.random(in: -10...30) }
}

func calculateAverageTemperature(for records: [Double]) async -> Double {
    let total = records.reduce(0, +)
    let average = total / Double(records.count)
    return average
}

func upload(result: Double) async -> String {
    "OKet"
}

func processWeather() async throws {
    var records = await fetchWeatherHistory()
    var average = await calculateAverageTemperature(for: records)
    var response = await upload(result: average)
    print("Server response: \(response)")
    return
}

do {
    try await processWeather()
} catch let error {
    print(error.localizedDescription)
}

I am getting this output (along with the error:

Server response: OKet
Playground execution failed:

error: execution stopped with unexpected state.
error: Execution was interrupted.
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.

what is the error about, do you know? And how to fix it?


Solution

  • You need to tell Playgrounds that you are doing asynchronous work by setting needsIndefiniteExecution to true and calling finishExecution when you are done.

    
    PlaygroundPage.current.needsIndefiniteExecution = true
    do {
        try await processWeather()
    } catch let error {
        print(error.localizedDescription)
    }
    PlaygroundPage.current.finishExecution()