在swift脚本中等待异步调用

Gag*_*ngh 7 command-line asynchronous swift

我正在编写一个swift脚本,在终端中运行,向后台线程调度几个操作.在完成所有调度之后,没有任何额外的努力,代码到达文件的末尾并退出,也杀死我的后台操作.在我的后台操作完成之前,保持swift脚本活着的最佳方法是什么?

我提出的最好的是以下,但我不相信这是最好的方式,甚至是正确的.

var semaphores = [dispatch_semaphore_t]()
while x {
  var semaphore = dispatch_semaphore_create(0)
  semaphores.append(semaphore)
  dispatch_background {
    //do lengthy operation
    dispatch_semaphore_signal(semaphore)
  }
}

for semaphore in semaphores {
  dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}
Run Code Online (Sandbox Code Playgroud)

jas*_*n z 8

除了使用之外dispatch_groups,您还可以执行以下操作:

yourAsyncTask(completion: {
    exit(0)
})

RunLoop.main.run()
Run Code Online (Sandbox Code Playgroud)

一些资源:


Gag*_*ngh 2

感谢 Aaron Brager,他 在 Swift Command Line Tool 中链接了多个工作人员

这就是我用来找到答案的方法,使用dispatch_groups来解决问题。