以下代码在延迟后不会打印你好。
有什么不对吗?
func delay(seconds delay:Int, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(delay)) {
closure()
}
}
delay(seconds: 5) {
print("hello")
}
答案 0 :(得分:0)
我通过创建一个runloop来实现它,否则程序只是退出而不调用异步块。如果您正在为iOS应用程序开发,则不应该这样做。
var keepAlive = true
func delay(seconds delay:Int, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(delay)) {
closure()
}
}
delay(seconds: 5) {
print("hello")
keepAlive = false
}
let runLoop = RunLoop.current
while keepAlive && runLoop.run(mode: .defaultRunLoopMode, before: Date(timeIntervalSinceNow: 0.1)) {}
答案 1 :(得分:-2)
let delayInSeconds = 5.0
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {
print("hello")
}