所以,我有一个 Swift 命令行程序:
import Foundation
print("start")
startAsyncNetworkingStuff()
RunLoop.current.run()
print("end")
代码编译没有错误。异步网络代码运行得很好,获取它的所有数据,打印结果,并最终调用它的完成函数。
如何让完成函数跳出当前运行循环,以便打印最后一个“结束”?
添加:
将 RunLoop.current.run() 替换为以下内容:
print("start")
var shouldKeepRunning = true
startAsyncNetworkingStuff()
let runLoop = RunLoop.current
while ( shouldKeepRunning
&& runLoop.run(mode: .defaultRunLoopMode,
before: .distantFuture ) ) {
}
print("end")
设置
shouldKeepRunning = false
在异步网络完成函数中仍然不会导致打印“end”。 (这是通过将 shouldKeepRunning = false 语句与实际打印到控制台的打印语句括起来进行检查的)。缺少什么?
最佳答案
对于命令行界面,使用此模式并将完成处理程序添加到您的AsyncNetworkingStuff(感谢 Rob 的代码改进):
print("start")
let runLoop = CFRunLoopGetCurrent()
startAsyncNetworkingStuff() { result in
CFRunLoopStop(runLoop)
}
CFRunLoopRun()
print("end")
exit(EXIT_SUCCESS)
请不要使用难看的 while
循环。
更新:
在带有 async/await 的 Swift 5.5+ 中,它变得更加舒适。不再需要维护运行循环。
将文件 main.swift
重命名为其他名称,并像在普通应用程序中一样使用 @main
属性。
@main
struct CLI {
static func main() async throws {
let result = await startAsyncNetworkingStuff()
// do something with result
}
}
结构的名称是任意的,静态函数 main
是必需的并且是入口点。
关于swift - 如何退出runloop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43825263/