user
user

Reputation: 445

Swift timer returning previous if statement without criteria being met

I have a workout timer which goes like this. 30 seconds of working out -> 10 seconds of rest. I have an if statement to print out some text, but for some reason they are both rapidly called at the same time instead of just the one that fits the If criteria. Any idea why? I've tried adding return at the bottom of each case but then neither are called after the first fire.

var restBreaks: [Double] = [30, 60]
    
    var startTime = Date.timeIntervalSinceReferenceDate
    Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) { [self] timer in
        
        let time = Date.timeIntervalSinceReferenceDate - startTime
        
        self.seconds = time
        
        print(time)
        
        for restLocation in restBreaks {
            if time >= restLocation && time <= restLocation + 10 {
                print("RESTING")
            } else {
                print("WORKOUT")
            }
        }
        
        // Restarting timer
        if time >= 90 {
            startTime = Date.timeIntervalSinceReferenceDate
        }
    }

Result: (when is resting period) as you can see it's printing out "WORKOUT!"

RESTING
WORKOUT!
RESTING
RESTING
RESTING
WORKOUT!
RESTING
RESTING
RESTING
WORKOUT!
RESTING

Upvotes: 0

Views: 85

Answers (1)

your code logic is not what you are trying to achieve. Try something like this:

struct ContentView: View {
    @State private var seconds: Double = 0.0
    @State private var restDuration: Double = 4.0
    
    var body: some View {
        Text("workout timers").onAppear {
            var breakIndex = 0
            // must be of the form x, and at least x+restDuration
            let restBreaks: [Double] = [5.0, 15.0]
            
            var startTime = Date.timeIntervalSinceReferenceDate
            Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
                let time = Date.timeIntervalSinceReferenceDate - startTime
                self.seconds = time

                if breakIndex < restBreaks.count {
                    if time >= restBreaks[breakIndex] && time <= restBreaks[breakIndex] + restDuration {
                        print("---> RESTING time: \(time) breakIndex: \(breakIndex) rest at: \(restBreaks[breakIndex]) to: \(restBreaks[breakIndex] + restDuration)")
                    } else {
                        print("WORKOUT time: \(time)")
                    }
                }
                
                if breakIndex+1 < restBreaks.count && time >= restBreaks[breakIndex] + restDuration {
                    breakIndex = breakIndex + 1
                }
 
                // Restarting timer
                if time >= 20 {
                    startTime = Date.timeIntervalSinceReferenceDate
                    breakIndex = 0
                }
            }
            
        }
    }
}

Upvotes: 1

Related Questions