Swift Script that uses asynchronous code

Overview:

I have a swift script that uses asynchronous code. I would like the script to wait till the asynchronous completes.

Questions:

  • What is the preferred way to wait till the asynchronous code is executed ?
  • I have made an attempt, however it keeps periodically checking, is there a better way to do it ?

Code:

import Foundation

print("Beginning")

DispatchQueue.main.asyncAfter(deadline: .now() + 4) {

    print("async")
}

print("End")

My attempt (not so elegant, keeps checking):

var isDone = false

print("Beginning")

DispatchQueue.main.asyncAfter(deadline: .now() + 4) {

    print("async")
    isDone = true
}

while !isDone &&
    RunLoop.current.run(mode: .default, before: Date() + 0.1) {
        
        print("waiting ...")
}

print("End")

For dispatch, you want to use dispatchMain. That will start the loop which waits and executes blocks on the main queue. Note that it never returns - it will keep looping and waiting forever - so you need to exit the program another way.

One way to do that is to use the POSIX exit function.

import Foundation

print("Beginning")

DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
    print("async")
    exit(0) // <- POSIX 'exit' function will close the program
}

dispatchMain() // <- This function never returns.
2 Likes

Wow !!! This is pretty cool, thank you so much !! Saved my day

I guess I could pass non-zero numbers in exit like exit(2) for failures.

You're welcome! And that's right; non-zero codes typically denote failure.

See the notes on the manpage about exit codes. They suggest using EXIT_SUCCESS and EXIT_FAILURE (which are imported in to Swift) for maximum portability. I probably should have done that :sweat_smile:

1 Like

Thanks a lot, I am new to writing swift scripts and command line apps, your tips were very helpful.