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

Does this still apply?

Forums > 100 Days of SwiftUI

In practice, what this means is that if we have two SwiftUI views and we send them both the same struct to work with, they actually each have a unique copy of that struct; if one changes it, the other won’t see that change. On the other hand, if we create an instance of a class and send that to both views, they will share changes.

from https://www.hackingwithswift.com/books/ios-swiftui/why-state-only-works-with-structs

Have just tried in Version 11.3.1 (11C505) and

Apple Swift version 5.1.3 (swiftlang-1100.0.282.1 clang-1100.0.33.15)
Target: x86_64-apple-darwin19.0.0

And it seems that if I change one text field, the labels at top are updated correctly, also changing the other after and switching between text fields does seem to update correctly the instance of the structure.

2      

What you are describing is correct behavior. Because the User struct is marked with @State and you pass bindings to its properties to the two TextFields, changes in those fields will update the struct.

2      

@roosterboy I see, mmmm so maybe I didn't get the objective to change it to class?

2      

The objective of changing it to a class from a struct was instructive. In that article, Paul was showing why changing a @State property to a class wouldn't work.

I know that all sounds terribly theoretical, but here’s the twist: now that User is a class the property itself isn’t changing, so @State doesn’t notice anything and can’t reload the view. Yes, the values inside the class are changing, but @State doesn’t monitor those, so effectively what’s happening is that the values inside our class are being changed but the view isn’t being reloaded to reflect that change.

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.