Search code examples
swiftxcodecountdown

The countdown timer will not work because it will not accept local functions


Every time i try to define a function when i use the Timer.Scheduledtimer with selector. It shows the following error. I'm not sure how to get past this. Also i would like to know if there is anyway that i can connect a label to the countdown I.e. on the screen 0:59, 0:58, etc.

Thanks.

I have already tried various functions from different websites and the same problem always reemerges

var seconds = 0

var timer: Timer?

let countdownLabel: SKLabelNode! = {   
let label = SKLabelNode(fontNamed: "BubbleGum")
   label.zPosition = 2
   label.color = SKColor.white
   label.position = CGPoint(x: 0 - 130, y:self.frame.size.height/15 
+ 390)
   return label
    }()
    countdownLabel.text = String(seconds)

    func counter (){
        seconds -= 1
        countdownLabel.text = String(seconds)
        if (seconds == 0)
        {
            timer!.invalidate()
        }

    }


    timer = Timer.scheduledTimer(timeInterval: 1, target: self, 
  selector: #selector(counter), userInfo: nil, repeats: true)



    self.addChild(countdownLabel)



}

This is the error message that comes up: Argument of '#selector' cannot refer to local function 'counter()'


Solution

  • Either annotate your counter function with @objc or use a closure

    @objc func counter () {
       ...
    }
    

    Using a closure:

    timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { timer in
        seconds -= 1
        countdownLabel.text = String(seconds)
        if (seconds == 0)
        {
            timer!.invalidate()
        }
    }