[英]create while loop on timer (swift3)
下面的代码在编译后即刻完成。 我希望计数器每秒增加1。 因此,该程序应运行556秒。 计数器每秒增加1。
var counter = 0
while true {
counter += 1
print(counter)
if counter == 556 {
break
}
}
您的代码中没有任何内容导致它每秒执行一个步骤。
Timer类非常适合此操作。
如果您只需要支持iOS 10.0和更高版本,那么新的基于块的计时器方法scheduledTimer(withTimeInterval:repeats:block:)
是一个不错的选择。
var counter = 0
weak var timer: Timer?
timer = Timer.scheduledTimer(withTimeInterval: 1.0,
repeats: true) {
theTimer in
counter += 1
print(counter)
if counter == 10 {
print("Counter = 10. theTimer = \(theTimer)")
theTimer.invalidate()
}
}
如果需要支持旧版本的iOS,则需要使用使用选择器的版本来调用实例方法: scheduledTimer(timeInterval:target:selector:userInfo:repeats:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.