Have 2 Task with for loops run concurrently?

Say I want to run a Task, with a for loop. Then have another Task with a for loop. And have these both run concurrently. Is there a way?

I tried doing this:

func stepAsyncStep(id: String, number: Int) async {
    if number % 10000 == 0 {
        print("chirp \(id) @ \(number)")
    }
}

func somethingAsync(id: String) async {
    for i in 0...100_000 {
        await stepAsyncStep(id: id, number: i)
    }
}

Task.detached {
    print("task a begin")
    await somethingAsync(id: "a")
    print("task a end")
}

Task.detached {
    print("task b begin")
    await somethingAsync(id: "b")
    print("task b end")
}
task a begin
chirp a @ 0
chirp a @ 10000
chirp a @ 20000
chirp a @ 30000
chirp a @ 40000
chirp a @ 50000
chirp a @ 60000
chirp a @ 70000
chirp a @ 80000
chirp a @ 90000
chirp a @ 100000
task a end
task b begin
chirp b @ 0
chirp b @ 10000
chirp b @ 20000
chirp b @ 30000
chirp b @ 40000
chirp b @ 50000
chirp b @ 60000
chirp b @ 70000
chirp b @ 80000
chirp b @ 90000
chirp b @ 100000
task b end

The only way I can make these run in parallel is to add sleeps into the loops. Is there any way to make then run concurrently without Task.sleep ?

I also tried a TaskGroup, this doesn't work either. Crying for help here.

I don't know if that's what you are looking for. Here, a and b start, execute, then end. But values are not intertwined.

DispatchQueue.main.async {
    Task {
        print("task a begin")
        await somethingAsync(id: "a")
        print("task a end")
    }
}
    
DispatchQueue.main.async {
    Task {
        print("task b begin")
        await somethingAsync(id: "b")
        print("task b end")
    }
}

Which results in:

task a begin
task b begin
chirp a @ 0
chirp a @ 10000
chirp a @ 20000
chirp a @ 30000
chirp a @ 40000
chirp a @ 50000
chirp a @ 60000
chirp a @ 70000
chirp a @ 80000
chirp a @ 90000
chirp a @ 100000
task a end
chirp b @ 0
chirp b @ 10000
chirp b @ 20000
chirp b @ 30000
chirp b @ 40000
chirp b @ 50000
chirp b @ 60000
chirp b @ 70000
chirp b @ 80000
chirp b @ 90000
chirp b @ 100000
task b end

EDIT: see my comments below to this post.

Interesting. What I got this with this code both in a Xcode playground project and from a command line build is:

task a begin
task b begin
chirp a @ 0
chirp b @ 0
chirp a @ 10000
chirp b @ 10000
chirp b @ 20000
chirp a @ 20000
chirp b @ 30000
chirp a @ 30000
chirp b @ 40000
chirp a @ 40000
chirp b @ 50000
chirp a @ 50000
chirp b @ 60000
chirp a @ 60000
chirp a @ 70000
chirp b @ 70000
chirp a @ 80000
chirp b @ 80000
chirp b @ 90000
chirp a @ 90000
chirp a @ 100000
chirp b @ 100000
task b end
task a end

swift-driver version: 1.62.15 Apple Swift version 5.7.2 (swiftlang-5.7.2.135.5 clang-1400.0.29.51) Target: x86_64-apple-macosx13.0 (OS X 13.2.1)

In a command line build I added at the end:

while true {

}

To keep the process running until the output came, then ctrl-c to abort.

Have 2 Task with for loops run concurrently?
 
 
Q