Created
August 15, 2024 17:36
-
-
Save bannzai/98e5771d4ecb5c85f0ec1f2851701ecf to your computer and use it in GitHub Desktop.
Tick.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage