0

How make CountdownTimer and how make let elapsed = public var . I want to make the variable constantly decrease life. For example, as in Tamagotchi - You need to constantly feed the animal so that it does not die. This timer should continuously run until it reaches 0. When the tamagotchi eats, the value is again added to the variable, which decreases over time.

class Stopwatch: ObservableObject {
    /// String to show in UI
    @Published private(set) var message = "Not running"
    /// Is the timer running?
    @Published private(set) var isRunning = false
    /// Time that we're counting from
    private var startTime: Date? { didSet { saveStartTime() } }
    /// The timer
    private var timer: AnyCancellable?
    init() {
        startTime = fetchStartTime()
        if startTime != nil {
            start()
        }
    }
}

extension Stopwatch {
    func start() {
        timer?.cancel()  // cancel timer if any
        if startTime == nil {
            startTime = Date()
        }
        message = ""
        timer = Timer
            .publish(every: 0.1, on: .main, in: .common)
            .autoconnect()
            .sink { [weak self] _ in
                guard
                    let self = self,
                    let startTime = self.startTime
                else { return }
                let now = Date()
                let elapsed = now.timeIntervalSince(startTime)
                guard elapsed < 60 else {
                    self.stop()
                    return
                }
                self.message = String(format: "%0.1f", elapsed)
            }
        isRunning = true
    }
    func stop() {
        timer?.cancel()
        timer = nil
        startTime = nil
        isRunning = false
        message = "Not running"
    }
}

private extension Stopwatch {
    func saveStartTime() {
        if let startTime = startTime {
            UserDefaults.standard.set(startTime, forKey: "startTime")
        } else {
            UserDefaults.standard.removeObject(forKey: "startTime")
        }
    }
    func fetchStartTime() -> Date? {
        UserDefaults.standard.object(forKey: "startTime") as? Date
    }
}

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • 1
    What errors do you get? What does not work? What does `how make let elapsed = public var` mean? – burnsi Apr 09 '22 at 23:26
  • you can use assign instead of sending it down the sink – malhal Apr 10 '22 at 07:31
  • Assuming you even still have this question, tell us what behavior you are experiencing and how it differs from what you were expecting. Obviously, if you've solved this already either (a) if you think the answer is helpful to others, [post an answer](https://stackoverflow.com/help/self-answer) to your own question; or (b) delete this question. – Rob May 27 '22 at 19:18

0 Answers0