Async and Await code doesn't work on command line tools but works on Xcode playgrounds

I am running Mac OS 12.1 and Xcode 13.2.

My code is the following:

import Foundation
import Cocoa

func trapezoid(_ begin: Double, _ end: Double,_ n: Int) async -> Double {

    let hc = (end-begin)/Double(n)
    var h = begin
    var result = 0.0

    for _ in 0...n{
        
        result += h*h + (h+hc)*(h+hc)
        h = h+hc
    }

        return result * (hc/2)
}

Task{
    let answer1 = await trapezoid(0, 1, 10000)
    let answer2 = await trapezoid(1, 2, 10000)
    print(answer1)
    print(answer2)
}

With playgrounds I get the following correct result:

0.33343334500044286
2.333733355000306

However, when I use the exact same code in an Xcode project using Command Line Tools, the program just returns with exit code 0 and no output. I am not sure what my error is or if it is an Xcode bug.

Answered by DTS Engineer in 698428022

The situation with async main has only just stabilised. See SE-0323 Asynchronous Main Semantics for the details. Note that this implemented in Swift 5.5.2, which is part of the just-released Xcode 13.2. I’ve not tried it myself yet (-:

Share and Enjoy

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

You have to define a main function marked with the @main attribute containing your Task.

Playgrounds are special in a way that they run all top level code automatically, normal swift programs don't do that.

Accepted Answer

The situation with async main has only just stabilised. See SE-0323 Asynchronous Main Semantics for the details. Note that this implemented in Swift 5.5.2, which is part of the just-released Xcode 13.2. I’ve not tried it myself yet (-:

Share and Enjoy

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

Async and Await code doesn't work on command line tools but works on Xcode playgrounds
 
 
Q