定时器间隔不触发

Timer Interval not firing

考虑这段代码:

import Foundation
import PlaygroundSupport

class Test
{
    var interval:Timer?
    var counter = 0

    func start()
    {
        print("Starting ...")
        interval = Timer.scheduledTimer(withTimeInterval: 1, repeats: true)
        {
            timer in
            self.counter += 1
            print(self.counter)
            if (self.counter < 10) { return }

            self.interval?.invalidate()
            self.interval = nil
            print("Done!")
            PlaygroundPage.current.finishExecution()
        }
        interval?.fire()
    }
}


PlaygroundPage.current.needsIndefiniteExecution = true
var test = Test()
test.start()

运行 这在 Xcode 8.3.3 游乐场,但间隔从未开始。我错过了什么?

简单的答案是将其添加到您的游乐场:

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

当使用 playground 时,默认情况下 playground 运行所有代码然后停止,它不知道等待计时器。这段代码只是告诉 playground 继续等待发生的事情。