|
Can somone explain why the following code doesn't succeed at changing the value of the title. Just click on "Add" first and then "Change value". I know there's other ways to do this but I just want to understand why it's not working. if you
|
|
In order to make your class to emit changes you have to make it @Observable First
Second make the class Observable and you can remove @Published as it will be in any case publishing changes
Now, everything works as, as soon as there is a change the object will publish the changes to view. |
|
Now what if it was a struct instead of a class?
|
SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates. Sponsor Hacking with Swift and reach the world's largest Swift community! |
|
Here you go:
|
|
Here is the way to work with both. In the below example you can separate the model from the view.
|
|
Thanks for that. And that's precisely what I'd like to understand. If using a Struct, why does
Work and not
|
|
For that you need to tell the difference between value types and reference types. Structs are value types and Classes are reference types. So basically when you create a struct and then assign it to a different variable you copy item and create kind of duplicate. In classes it works differently and you create a reference aka pointer to the same object in memory, so when you make updates to the class item you change it from different places. In structs you create different object and if you make updates you change updates to different objects not the same one. Hope from the below code and comments it becomes clear what is going on if you do your way and why there is no update. So simply using the code offered by me, you avoid several lines of unnecessary code and get the same result.
|
|
Haaaaa. Yes that should have ticked in my head.... of course. However since it is possible to mutate the property of the struct without specifically marking it with mutating func ( items[index].title = "Super Test"). Is it because of the @State var items = [TodoItem]() wrapper? |
|
View structures is diffent large topic, but shortly, yes @State works in such a way that you don't need to use mutating functions. So in your case your code works that way:
In your initial code with struct point 3 was never reached so the view was the same. |
|
Thanks heeps. Even with years of experience in ObjC and Swift, SwiftUI manages to make me wonder. There's so much behind the scene... |
SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.
Sponsor Hacking with Swift and reach the world's largest Swift community!
You need to create an account or log in to reply.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.