在计时器上创建 while 循环 (swift3)
create while loop on timer (swift3)
下面的代码编译时立即完成。我希望计数器每秒加 1。所以程序应该 运行 556 秒。计数器每秒增加 1。
var counter = 0
while true {
counter += 1
print(counter)
if counter == 556 {
break
}
}
您的代码中没有任何内容会使其每秒执行一步。
定时器 class 非常适合这个。
如果你只需要支持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:)
下面的代码编译时立即完成。我希望计数器每秒加 1。所以程序应该 运行 556 秒。计数器每秒增加 1。
var counter = 0
while true {
counter += 1
print(counter)
if counter == 556 {
break
}
}
您的代码中没有任何内容会使其每秒执行一步。
定时器 class 非常适合这个。
如果你只需要支持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:)