In I want to make something change every X seconds so I can use a timer like this example:

This seems to work but won't the timer get reset/recreated every time this view struct gets recreated by SwiftUI? Shouldn't the timer be a StateObject?

· · Web · 2 · 0 · 0

@bigzaphod yeah, def don’t store mutable class references directly on the view struct like that. You might be able to get away with a plain for the timer instead, since it’s not directly observable anyways, but in general factoring everything in a “view model” ObservableObject would be cleaner for something more complex.

@bigzaphod there should have been a “@“ “State” in there that seems to have been eaten.

@axiixc using State was my instinct here so I'm surprised to see something from Paul Hudson about SwiftUI that seems to be wrong - but maybe it is.

@bigzaphod might just be a typo? I think with “@/State var” added that example would be correct.

@bigzaphod page is down so I couldn’t check, but … why is a timer put in a view?

I’m thinking in c# And need to learn swift 😂

But in c# the timer isn’t something visual… I just put it higher in the hierarchy and have a visual updated only when showing. Hence confusion 😵‍💫

@antijingoist well that'd be the "normal" way to handle these things but is kinda weird and has some very unusual patterns made possibly by abusing various language features. So sometimes stuff just isn't... obvious. 😛

@antijingoist nah, it's just that's a bit odd and I think it's partly because despite Apple's best efforts with WWDC videos and such, the internals and how/what it does is still not really well explained.

Sign in to participate in the conversation

The original server operated by the Mastodon gGmbH non-profit