如何在swift中添加时间延迟 [英] How to add a time delay in swift
本文介绍了如何在swift中添加时间延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用swift编写一个互动游戏,我需要知道如何在重复动作之间添加一个暂停。我必须这样做的方式是for循环。如下:
I am writing an interactive game in swift, and I need to know how to add a pause in between repetitive actions. The way I have to do this is in a for loop. As follows:
for i in 1...10 {
println("Hello!")
}
任何人都可以找到修改此代码的方法,以便每秒打印一个Hello ?
Can anyone find a way to modify this code so that it prints one "Hello" per second?
此外,如果循环的swift 立即返回,我认为延迟代码不会起作用那么,这里是另一个使用函数的迭代解决方案,如果for循环没有这个函数应该有效。
Also, if swift for
loops are instantly returning, i don't think that delay code would work in there, so here is another iterative solution using functions that should work if the for loop doesn't.
func printer() {
println("Hello")
delay()
}
func delay() {
//delay code goes here
printer()
}
任何帮助都将不胜感激。
Any help would be greatly appreciated.
谢谢。
推荐答案
试试这个
for i in 1...10{
var timeToDelay = Double(i)
delay(timeToDelay) {
println("Hello")
}
}
func delay(delay:Double, closure:()->()) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(delay * Double(NSEC_PER_SEC))),dispatch_get_main_queue(), closure)
}
这篇关于如何在swift中添加时间延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文