UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

D47: Habit Tracker

Forums > 100 Days of SwiftUI

Hi,

Trying to figure out what is the best approach to deal with updating an Activity's count in the Activity detail view and mutating the array in the Activities ObservableObject at the same time.

I first started trying to make Activity a Class rather than a Struct (which Paul suggested), so that I could make it Observed and publish the changes to its count, but I struggled with conforming it to Codable with a @Published property (even if this helped). Didn't work out in the end as the count would update in the detail view, but not in the list, until I would add another Activity item for instance.

Ended up taking an approach that I'm afraid is not elegant, i.e passing both the Activities and Activity instances to the detail view, and creating a copy of the Activity with the incremented count, and then inserting that copy in lieu of the original Activity in the Activities items array.

Here is the working code on a gist

Really curious to hear how others have tackled this problem.

3      

Hi @mjarraya , I too worked on making a habit tracker after learning swiftui. I would suggest shifting incrementCount function to your Activities class as its method, and you can just call your class method on button press. You can refer my code at https://github.com/Deepesh22/Habit-Tracker/blob/master/HabitTracker/Habit.swift .

Hope it helps.

2      

If you do not want to pass your ObservableObject to the DetailsView and want to make the changes directly in the DetailsView, you can solve this with an @Binding. See my gist https://gist.github.com/Ma-He/6b9ebff24061884fde8e2132692a9aa3 Interesting for you are lines 68, 152 and 153.

I hope it helps you.

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.