在Swift中暂停循环迭代

时间:2018-04-23 06:51:16

标签: swift

我目前有这样的循环,但我意识到使用睡眠不是这样做的方法。我希望它需要60秒才能在循环中进行下一次迭代。我怎么能以更好的方式处理这个问题?谢谢!

for count in 0...60 {
   if arrayOfOptions.contains(count) {
      // play a sound.     
   }
   sleep(1) // pause the loop for 1 second before next iteration
}

5 个答案:

答案 0 :(得分:2)

我建议使用计时器:

  1. 将循环移动到函数

    func playSound(for value: Int, in array: [Int]) {
        if array.contains(value) {
            playSound()
        }
    }
    
  2. 创建计时器:

    Timer.scheduledTimer(withTimeInterval: 1.0, 
                         repeats: true) { [weak self] _ in
                             guard let array = self?.array, let index = self?.currentIndex else { return }
                             self?.playSound(for: index, in: array)
                             self?.index = index + 1
                         })
    

答案 1 :(得分:0)

您可以通过遵循 recursion 方法来实现,例如:

var count = 0
func playSound(delayInSeconds: Int) {
    // here you can do your functionality
    print("\(count): do my thing")

    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(delayInSeconds)) {
        if self.count < 61 {
            self.count += 1
            self.playSound(delayInSeconds: delayInSeconds)
        }
    }
}

因此你称之为:

playSound(delayInSeconds: 2)

答案 2 :(得分:0)

这是一个延迟执行指定时间的函数。

//MARK: Delay function

func delay(_ delay:Double, closure:@escaping ()->()) {
    DispatchQueue.main.asyncAfter(
        deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}

你可以使用这样的功能:

delay(2)  //Specify the amount of time - In your case "1" second
{
      //Put the delayed code here
}

希望这可以帮助你。

答案 3 :(得分:0)

我同意艾哈迈德·F的观点,即递归可能是要走的路。我的例子是解决方案在同一个球场,不同之处在于我通过索引以避免为此目的而拥有一个类范围的变量。 (+一些小的文体差异)。

func playSound(fromIndex index: Int = 0)) {
    guard index < arrayOfOptions.count else { return } // safety first
    if arrayOfOptions.contains(index) {
        // play a sound
    }
    guard index <= 60 else { return }

    Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { _ in
        self.playSound(fromIndex: index+1)
    }
}

这只是以playSound()

开头

@PurplePanda如果想要运行整个数组,将guard语句更改为guard index < arrayOfOptions.count else { return }会更明智。这也是我添加初始保护声明的原因,因为没有技术理由假设数组不为空...

扩展这个并让函数接收数组可能很容易,但这显然取决于你的具体要求......

答案 4 :(得分:-1)

从for循环调用此函数: -

//MARK: Delay func 
func delay(_ delay:Double, closure:@escaping ()->()) {
    DispatchQueue.main.asyncAfter(
        deadline: DispatchTime.now() + Double(Int64(delay * 
    Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}

示例: -

for() {
    //your code
    self.delay(2) {

    }
    //Your code
}