|
Hi everyone. I recently finished the project on Day 47, but I'm still failing to understand how SwiftUI treats data between views. Some explanation would be appreciated. In my ActivityDetail view, I was trying to update the timesCompleted property of the Activity struct directly, by incrementing the count with a button and then setting the new value directly with this function. The code checked out, but it wouldn't let me change the timesCompleted property because it stated that "activity" was a constant (even though I declared it with var). Essentially, I tried to modify one property in the struct that the class contained and it didn't work.
Eventually I found that I needed to swap the Activity item in the Activities array completely, using this function:
My question is: why isn't it possible to modify only the timesCompleted property? Why does Swift require a new instance of Activity to replace the old one? Full code here of code that didn't work (error message cannot assign to property: 'activity' is a 'let' constant:
|
|
hi, when you write this code:
you need to recognize that the you can, of course, update individual items of an array, so replacement does work. hope that helps, DMG |
|
Thank you very much for the explanation! I understand now how my original code wouldn't have worked. |
BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.
Sponsor Hacking with Swift and reach the world's largest Swift community!
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.
Link copied to your pasteboard.