Search code examples
swiftclassobjectinitializer

Start a timer when Object is created


I like a timer to start when an object is created. (see code below in playground). My problem is the timer seem to never start.

How can I start a timer when a Object is created?

import Foundation

class Test {
    var counter = 60
    var timer = Timer()
    init() {
        timer = .scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
    }
    @objc func updateCounter() {
        // example functionality
        if counter > 0 {
            counter -= 1
            print(counter)
        } else {
            counter = 60
        }
    }
}

var newTest = Test()

Solution

  • What you need is to import PlaygroundSupport and set playground page needsIndefiniteExecution to true

    import PlaygroundSupport
    PlaygroundPage.current.needsIndefiniteExecution = true