0

Consider this code:

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()

Running this in Xcode 8.3.3 Playground but the interval never starts. What am I'm missing?

BadmintonCat
  • 9,416
  • 14
  • 78
  • 129
  • I'm not at my computer right now, but google "playground indefinite execution" – Kevin Sep 20 '17 at 01:05
  • @Kevin I updated my example as per https://stackoverflow.com/questions/24058336/how-do-i-run-asynchronous-callbacks-in-playground#24066317 for Playground but still not firing. – BadmintonCat Sep 20 '17 at 01:15
  • Works fine for me when I copy and paste your code. – Kevin Sep 20 '17 at 01:18

1 Answers1

1

The simple answer is to add this to your playground:

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

When using a playground, by default the playground runs all the code and then stops, it doesn't know to wait for the timer. This code just tells the playground to keep waiting for something to happen.

Kevin
  • 53,822
  • 15
  • 101
  • 132
  • Now it works for me too! Had the iOS simulator still running in the background from yesterday and quitting it & restarting Xcode did the trick. – BadmintonCat Sep 20 '17 at 01:29