I'd like to use @AppStorage("interval")
to initialize timer
. I cannot do this in the struct initialization because I'll get an error. But if I try to do declare timer
first and initialize it in startTimer()
, I get all sorts of errors as well. What's the best way to make sure interval
is available to initialize timer
? Here's the relevant code:
struct ContentView: View {
@AppStorage("interval") var interval = 5.0
@State private var timer = Timer.publish(every: interval, on: .main, in: .common).autoconnect()
//or try this:
@State private var timer: Publishers.Autoconnect<Timer.TimerPublisher>?
//or try this:
@State private var timer: Publishers.Autoconnect<Timer.TimerPublisher>? = nil
init() {
startTimer()
}
func startTimer() {
timer = Timer.publish(every: interval, on: .main, in: .common).autoconnect()
}
func stopTimer() {
timer.upstream.connect().cancel()
}
}