Skip to content

Instantly share code, notes, and snippets.

@bannzai
Created August 15, 2024 17:36
Show Gist options
  • Save bannzai/98e5771d4ecb5c85f0ec1f2851701ecf to your computer and use it in GitHub Desktop.
Save bannzai/98e5771d4ecb5c85f0ec1f2851701ecf to your computer and use it in GitHub Desktop.
Tick.swift
import Combine
import SwiftUI
class _Tick: ObservableObject {
@Published var now: Date = .now
let timer: Publishers.Autoconnect<Timer.TimerPublisher>
init(every: TimeInterval = 1) {
timer = Timer.publish(every: every, on: .main, in: .common)
.autoconnect()
timer.assign(to: &$now)
}
deinit {
timer.upstream.connect().cancel()
}
var today: Date {
Calendar.autoupdatingCurrent.date(from: Calendar.autoupdatingCurrent.dateComponents([.year, .month, .day], from: now))!
}
}
@propertyWrapper
struct Tick: DynamicProperty {
@StateObject private var tick: _Tick
init(every: TimeInterval = 1) {
_tick = StateObject(wrappedValue: .init(every: every))
}
var wrappedValue: _Tick {
tick
}
}
@bannzai
Copy link
Author

bannzai commented Aug 15, 2024

Usage

struct ContentView: View {
  @Tick var tick
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment