所以,我有一个 Swift 命令行程序:
import Foundation
print("start")
startAsyncNetworkingStuff()
RunLoop.current.run()
print("end")
代码编译没有错误。异步网络代码运行良好,获取所有数据,打印结果,并最终调用其完成函数。
如何让完成函数突破上述当前运行循环,以便打印最后一个“结束”?
Added:
将 RunLoop.current.run() 替换为以下内容:
print("start")
var shouldKeepRunning = true
startAsyncNetworkingStuff()
let runLoop = RunLoop.current
while ( shouldKeepRunning
&& runLoop.run(mode: .defaultRunLoopMode,
before: .distantFuture ) ) {
}
print("end")
Setting
shouldKeepRunning = false
在异步网络完成函数中仍然不会导致打印“end”。 (这是通过将 shouldKeepRunning = false 语句与实际打印到控制台的 print 语句括起来来检查的)。缺什么?
对于命令行界面,请使用此模式并将完成处理程序添加到您的异步网络东西(感谢 Rob 改进代码):
print("start")
let runLoop = CFRunLoopGetCurrent()
startAsyncNetworkingStuff() { result in
CFRunLoopStop(runLoop)
}
CFRunLoopRun()
print("end")
exit(EXIT_SUCCESS)
请不要使用丑陋的while
loops.
Update:
在带有 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
是强制性的,并且是入口点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)