|
Hi guys, I am trying to seperate the code in my View into a View and a model, and came up with the following model:
However when I modify Thanks for any help! |
|
Hi again! Let’s start with the idea of Environment. When you create and start your very first View in SwiftUI, the framework generates Environment for it. SwiftUI creates it automatically, and we don’t need to do something. SwiftUI uses Environment to pass system-wide settings like ContentSizeCategory, LayoutDirection, ColorScheme, etc. Environment also contains app-specific stuff like UndoManager and NSManagedObjectContext. So you cannot create Environment vars from classes, because Environment belongs to Views. Also, Xcode autogenerates Task class from your data model (from file TaskDataModel) and those data objects inherit ObservableObject. This means you see changes immediately published to your UI when data changes. So you don't need to create again TaskModel as it already generated by XCode as Task class behind the scenes. Also these items belong to the view not Task, as they are connected to fields on the View itself where you insert your data. So they should stay @State var in View itself.
You may want to create extension to Task instead to make it more view ready like so. Create a file Task extension:
so you can use those items without need to use nil coalescing. To simplify your MainView you can also extract some part of code into separate struct or even file like so. So it will be easier for you to read.
There are many many other options of course. All is up to you how you would like to see you project. Also some logic can be moved into an observable object instead. But this is another huge topic, and for such simple project it might be more pain than gain. |
|
If you wish to move all logic to your observable object you can refactor your code as follows:
PS. This is not the only way to arrange this. So other approaches are as good as this one :) |
|
Wow, thanks so much for the detailed answer! The stuff with Environment and State makes sense, and thanks so much for the suggested improvments too! |
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.