Home > Net >  How do I return a value from a function triggered by Timer
How do I return a value from a function triggered by Timer

Time:09-09

I have created a timer to trigger the function timerFire, every 5 seconds accepting the Double howHungry from another swift file.

The timer takes the value of howHungry and reduces it by 1 every time the timer fires and returns the new value.

Once the new value of howHungry is returned how can i retrieve the new value of howHungry to file1.swift?

As the original value is not being reduced the same value is sent each time

Console is currently showing:

Hunger value is 14.0
Hunger value is 14.0
Hunger value is 14.0

file1.swift

    let hungerTimer = myTimer()

    hungerTimer.startTimer(timerInitialValue: howHungry)

file2.swift

    func startTimer(timerInitialValue:Double){
    
        if timer == nil{ //Create a new timer for hunger if one doesn't exist
            timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(timerFire(sender:)), userInfo: timerInitialValue/*how hungry*/, repeats: true)
            print("New Timer Started")

        }else{ //If a timer does exist, end it and start a new one.

            timer!.invalidate()
            timer = nil
            print("Old Timer Stopped")
            timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(timerFire(sender:)), userInfo: timerInitialValue, repeats: true)
            print ("Now New Timer Started")
            print(timer)
        }
}

   @objc func timerFire(sender: Timer) -> Double{
        //get hungryDouble value from Timer       
        var hungryDouble = sender.userInfo as! Double
        //Reduce it by 1
        hungryDouble -= 1.0
        print("Hunger value is \(hungryDouble)")
        return(hungryDouble)
}

CodePudding user response:

You can add a callback inside file2.swift

var callback:((Double)->())?

@objc func timerFire(sender: Timer){
   //get hungryDouble value from Timer       
   var hungryDouble = sender.userInfo as! Double
   //Reduce it by 1
   hungryDouble -= 1.0
   print("Hunger value is \(hungryDouble)")
   callback?(hungryDouble)
} 

And inside file1.swift

let hungerTimer = myTimer()
hungerTimer.startTimer(timerInitialValue: howHungry)
hungerTimer.callback = { [weak self] res in
   print(res)
} 
  • Related