简体   繁体   English

在计时器上创建while循环(swift3)

[英]create while loop on timer (swift3)

The code below when compiled is completed instantly. 下面的代码在编译后即刻完成。 I would like the counter to add 1 every second. 我希望计数器每秒增加1。 So the program should run for 556 seconds. 因此,该程序应运行556秒。 Every second goes by the counter increase by 1. 计数器每秒增加1。

      var counter = 0

    while true {

        counter += 1

        print(counter)

        if counter == 556 {
            break
        }
    }

Nothing in your code causes it to do one step per second. 您的代码中没有任何内容导致它每秒执行一个步骤。

The Timer class is perfect for this. Timer类非常适合此操作。

If you only need to support iOS 10.0 and later, the new block-based timer method scheduledTimer(withTimeInterval:repeats:block:) is a good choice. 如果您只需要支持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()
  }
}

If you need to support older versions of iOS then you'll need to use the version that uses a selector to call an instance method: scheduledTimer(timeInterval:target:selector:userInfo:repeats:) 如果需要支持旧版本的iOS,则需要使用使用选择器的版本来调用实例方法: scheduledTimer(timeInterval:target:selector:userInfo:repeats:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM