How to read the values of timer? Swiftui

Viewed 184

I am trying to make the next condition in swift UI:

If the timer (hours) shows 23, then tryout = tryout + 1. However, it said that my code will never be executed. So, Is there any possibility to do that?

In my app user picks up the number of days till the deadline, and I am trying to make a deadline countdown through the timer. I need a solution to read hours in the timer, so I could save a new value when the timer reaches a new day.

Maybe you have other solutions (except Calendar, because I cannot add it in my app), I will be glad to hear them!

P.S. My Code Sample:

/////Timer
 let timer = Timer.publish(every: 3600, on: .main, in: .common).autoconnect()

/////Timer Func
func dayString(time: Int) -> String {
    let days   = Int(time) / 86400
    let hours   = Int(time) / 3600 % 24
    return String(format:"%02i", days)
    if hours == 23 {
        tryout = tryout + 1
    }
}
1 Answers

I'm not sure what you are trying to do, but you mention a problem with your function and I can help with that.

You have:

/////Timer Func
func dayString(time: Int) -> String {
    let days = Int(time) / 86400
    let hours = Int(time) / 3600 % 24
    return String(format:"%02i", days) // <- function returns
    if hours == 23 {                   // <- this will never run
        tryout = tryout + 1
    }
}

Because you are returning from your function, the code after it will never be executed, and this is what the compiler is telling you. You need to move the return to be the last expression

/////Timer Func
func dayString(time: Int) -> String {
    let days = Int(time) / 86400
    let hours = Int(time) / 3600 % 24
    if hours == 23 {
        tryout = tryout + 1
    }
    return String(format:"%02i", days)
}
Related