|
I am struggling to understand why this works. similar to the iExpense app where we created a struct then a class intialising the array of that struct and finally intialising that class in ContentView and passing that over to our Addview, i did the same thing here. I do not understand why this works but if i were to just simply create a class Photo and in my ContentView i initalise an array of that and pass that over to my PhotoView why can i not append anything to that array. i get this error, Cannot use mutating member on immutable value: 'self' is immutable. Why does the first method work and not this. Thanks in advance
|
|
|
|
the code works correctly but i am struggling to understand why it works.
and passing this into my new view and trying to append that to my list doesnt seem to work
and making it @State updates the array in PhotoView but not ContentView so i am confused as to why this works
i am confused as to why the second approach works and not the first, and what exactly is the benefit of the second approach |
|
Sorry, I didn't read your code to the end and I missed the second View. Structs in SwiftUI are by default immutable. That's a language feature which we have to accept. When you use variables that have to change you have to mark them with a property wrapper like @State , @Binding or @Bindable. So in your example we have to adapt the code which I gave to you (because I didn't see the Content View).
Your PhotoView should access the exact same variable. Now in your On the call side you have to use
This should do the trick and your ContentView should update. |
|
Thanks a lot for all the help i really appreciate it, i just have have one last doubt. When using @Bindable how do i preview my code because the preview required a $Bindable object. Also if i understand correctly, my [Photo] could not be appended to because of structs being immutable, but what if i made it into a class, it still doesnt work
and then in my contentView i made an array of Photo and pass that into my PhotoView, shouldn't it work because classes are mutable ? |
|
The View is immutable not your Photo and the View has to be a struct. You can't make it into a class. You need the property wrapper in the View (and they only work in a View). In your preview you should be able to use
|
SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!
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.