SwiftUI - Intro to MVVM | Example Refactor | Model View ViewModel
HTML-код
- Опубликовано: 26 ноя 2024
- Head to squarespace.co... to save 10% off your first purchase of a website or domain using code SEANALLEN.
In today's video I give you an introduction to the concept of the Model View ViewModel (MVVM) Architecture with SwiftUI. We will refactor a screen into a viewModel as an example. I explain the concept for those who have no idea what MVVM is so I keep it pretty basic. The general idea is to keep your business logic out of your views.This tutorial was created in Xcode 12.5 and Swift 5.4.
Starter Project Download:
www.dropbox.co...
If you like my teaching or presentation style, I've started creating my own courses:
seanallen.teac...
Twitter:
/ seanallen_dev
Link to my book - How I Became an iOS Developer:
gumroad.com/l/...
Hired.com:
hired.com/x/1n01g
Check out my podcast, iOS Dev Discussions:
itunes.apple.c...
Book and learning recommendations that help out the channel if you decide to purchase (Affiliate Links):
Paul Hudson's Hacking With Swift:
gumroad.com/a/...
Donny Wals - Combine:
gumroad.com/a/...
Mark Moeyken’s SwiftUI Books:
www.bigmountainstudio.com/swiftui-views-book/fzc51
Learn Advanced Swift Here:
gumroad.com/a/...
Ray Wenderlich Books:
store.raywende...
Ray Wenderlich Videos:
store.raywende...
Links to my iOS Dev Setup & iOS Dev Book Recommendations
www.amazon.com...
#swift #softwaredeveloper #iosdeveloper
I’ve heard several explanations of MVVM, but thinking of the view as being dumb makes perfect sense to me - I finally get it!
That's awesome to hear Paul; and exactly what I was going for. That's why I called it "Intro to MVVM" because I didn't want to get too deep into perfect definitions as that can be confusing to people just learning. I wanted to explain it in as "normal" terms as possible. Happy to hear it worked for you!
I don't know if you're the best teacher of the world, but your presentations and explanations are so clear that I've enrolled your free lessons for now, and it's so transparent that the way you are teaching is the best way for me to learn. It's complete, it's evolutive... You are my SwiftUI hero now! Many thanks to share your firsts lessons, it's showing how the way you teach is efficient. Please keep the way going on. I'm wishing the best for you! Best regards. Greg
I appreciate the kind words. It's a big deal to find someone who's teaching style resonates with you. Happy to hear that could be me :)
A great video Sean. Thank you for the real-world code example during the explanation. I would very much enjoy seeing more of your architectural explanations.
This is easily the most helpful video I have seen to explain SWIFTUI MVVM
Happy to hear it was helpful!
Would this refactor have been the same if we wanted to go with MVC rather than MVVM? I kinda struggle to find the difference between the two tbh.
Who knew I was passively making a MVVM.
This is clean stuff @sean. I can hardly find content that is so clean in iOS. Thanks a lot, please come up with a big how to build video with MVVM pattern. Much love ❤️
Glad you enjoyed it, Prajwal.
How does this compare to the MVC? Model-view-controller? It seems to me that your 'viewmodel' is doing the same thing a controller would in an MVC.
Something always felt wrong about putting functions in my view structs 😅 Thanks for this clear explanation! :)
Haha, now you know! Happy to help.
new bee in iOS, but quickly pick it up based on your videos, thanks a lot, no 1 iOS training online
Glad you like it!
That's exactly what I need, thank you, your videos are always great!
Happy to help, Lukas
You've helped me getting that darn @published / @observableobjec concept to sink in. Thanks!
Happy to hear it!
Great video! Really appreciate the "visual learning" stuff.
I am still catching up, so I have a lot of gaps in my knowledge and understanding of Swift, SwiftUI, SwiftData, etc. Your videos have been very helpful so far. The pace and focus of your videos are perfect. For this one, though, I am wondering how the advent of SwiftData changes the MVVM. Can you pull SwiftData context model into an Observable class model, or does SwiftData break the MVVM?
Thanks brother, it was simple and super crisp.
Glad it helped!
You are awesome!!! Love your style.
Thank you so much!!
Great video! Is it common to actually put the model in a separate file on its own? So that you have a more lcear 3 part division of the MVVM?
I believe how you organize your files (separate files or in the same file) is down to how you like to organize things. Which is very much personal preference.
great example for starter atleast..keep it up..one suggestion instead of calling getAppetizers function in onAppear, call in initializer in view model class
A great example to aid in learning this model. Thanks for sharing!
More like how react state management, I think I might have a good chance of learning swift quicker than I expected. Great tutorials 👏🏻 btw, just explains the point and saves us precious time.
Curious why the use of @stateobject in the view instead of @observedobject?
You can think of stateObject as a data source, if you don't use stateObject, the viewModel will be created again and cleaned when the view refreshes. ObservedObject should be used in classes you pass the StateObject.
Could you do a video breaking down Alerts and how you set it up in this video?
Dear Sean! i Have a question:
if I want to group the body parts to a structs, so in my body will be some like this:
HStack {
loadingView
ZStack {
searchingView
currentWeatherView
}
}
where I need to keep this structs? also in ViewModel, I think?
Great video, explained as it should be! Thank you for sharing your knowledge. Please keep going…
Do you have a full example of Android - like MVVM architecture where the networking isn't done at the VM level but at the data source level? This means that you have a View -> ViewModel -> Repository -> Local / Remote data source. When working at this level of abstraction the ViewModel knows nothing about where the data came from and it is up to the repository to determine where the data is taken from.
I've never written anything for Android, so I wouldn't know.
@@seanallen Alright so what I meant was that when you have only a ViewModel in your architectural layer and no more layers then your architecture is still kinda weak. If you had 2 more layers between the view and the actually network calls, let's call them a Repository and Data Source so we can compare to Android then repository gets the data from a data source (network call or local database) in which the calls actually occur in these classes. The repository is the only layer that knows where the data actually came from while ViewModel knows NOTHING about where the data came from and asks the Repository for the data, sometimes even combining multiple repository calls for one call. At the final stage, the 'dumb' View knows NOTHING about all of these layer either and is informed by the "smart" ViewModel about actions he is supposed to do when it is needed. That's a very basic explanation about current MVVM in Android, hopefully I explained it right so you got it
@@seanallen So to summarize what I meant - you are lacking more layers for this to be called MVVM in my opinion. The ViewModel alone is insufficient as you might want to combine multiple types of calls for one view which may be from a network, a local database or even a local API from your device
@@FckYouPlz So true, viewmodels aren't supposed to know where the data is coming from. I was an android developer for 3 years and now I write advanced level applications with SwiftUI and I never use viewmodels. You can just use repositories and make views observe them, so easy to sync subviews with main views without passing data between them.
@@Kaanozkaya24 as a SwiftUI illiterate here, you mean you can make your view structs bind to the data directly/almost-directly? At least a display friendly formatted/transformed data.
Excellent @sean short and straight
Sean, thank you! This vid was very helpful
What if multiple views share the same properties or methods? Should I create separate ViewModels, or share one ViewModel through passing along via initializers? When is a singleton the best option?
Thank you!!! Good example and clear explanation
Hi Sean, I've been watching your videos about iOS for almost 2 years. I love all the contents you've been creating. Thank you so much! I'm wondering if you could please create a video to explain the "iOS app system design" in senior level of ios interview. What exactly are they expecting, and what should we focus on during that round? MVVM is one thing I can think of, what about different layers, like data storage, API design, network, behavior improvement etc. Thank you again!!!
This is a good topic. Did you learn anything new about this?
Beautiful explanation. Thank you. Keep it up.
You mentioned having to use classes because of it persisting state, Do Swift structs not hold state?
Simplest explanation! thanks a lot
Thanks Sean. As always great tutorial. 🙌
TY Sean! Great video.
Glad you enjoyed it
Hi Sean, what about tutorial about HealthKit integration? For example just simple app that display some health data like blood glucose, insulin delivery etc.
Great video! I can wrap my head around those all property wrappers like StateObject, EnvironmentObject, ObservedObject ... What are the differences between them? Can you make a video about it?
I have the same question... still unclear after reading several articles.
Good and clear explanation! Thanks for that! 😃
Do you think it's a good idea to go with more complicated architectures like VIP in SwiftUI?
Even so it's hard to confirm to these architectures in SwiftUI but somehow it may be providing more uncoupled code
Hey Sean, I am having really difficulty with using my struct inside of a class. on different files. I always have an error. Would you recommend me a good source?
Excellent video and excellent content, as always. I'm now wondering how to have persistent user settings, since @AppStorage isn't made for classes. Do we have to go back to traditional Swift code like UserDefaults.standard.set() ?
Hi Sean, How can I move fetched results to viewmodel in order to complain with Apple design pattern. Do you know how? Thank you in advance
I don’t really get VeiwModel vs Controller? Couldn’t we just call the view model the controller?
Do you think Native(Swift) Loose its demand due to flutter in future??
Why u don't canceling previous task if you dispatch a new one?
Should network calls not be placed in the model?
Please Make Video for how to write Unit Tests
there used to be 69 comments until I got here.. Great abstractions, but you still have a global Mvvm architecture. about about something where each screen or set of screens is sort of a Plugin, all contained 1 MVVM folder. so you have multiple folders each with MVVM files, instead of having a global model folder or a global view folder.
Also, what role would you say an API call has in such a MVVM-model? Is it part of it like part of the VM or is it a separate thing?
To be honest, I don't really follow these acronym architectures perfectly. To me, not EVERYTHING has to fit in a specific box. But, if I had to say... I usually consider my networking layer as part of the model.
Please clarify an item for me in the step in the refactor where you connect the viewmodel (vm) to the list view. In the alert line the reference to the vm is made with $vm.(1) while every other reference is just vm.(3). Why the difference?
I can explain as I was wondering the same thing. So basically the "item" parameter in .alert() function expects Binding type. And $ sign requires there as it is the symbol to represent of using two-way binding. The other two functions doesn't require the parameter to be a Binding type.
Hi Sean, just one thing that you could rethink: according to the MVVM architecture, the ViewModel has nothing to do with any view, that's why it doesn't make sense for it to be together in the same folder with other views. The ViewModel even knows the views that are using it.
I’ve seen some people, Paul Hudson comes to mind, who place the ViewModel inside the view (as an extension). Others use the ViewModel for each model they gave.
@@JohnDoe19840 yes I've seen too. It works just for small projects, and is not really mvvm.
Why you used @StateObject instead of @ObservedObject?
The view being dumb makes complete sense to me but I am still always confused on how to split what goes into the view and viewModel.
the view is just whats on the screen that the person using the app sees and the view model basically takes the data from your model and does some logic ( like picking the data needed for the specific view) and then tells it to the view to be displayed
That was a great video. Thanks.
Thanks for the tutorial and for sharing the code Sean! Came at the perfect time as I’m getting deeper into SwiftUI👌
Shouldn't be @ObservedObject instead of @StateObject ??
Please use light theme in xcode, because i have problem with my eyes. 😢😢 Thanks ...
Why we are using Final before Class Name ?
to get rid of class could not be inherited
When you add "final" before a class, that means that it cannot be sub-classed.
I have one question,
What is the best way to share the view model in between the parent and child view controller.
Suppose i have ControllerA which is connected to view ModelA
Now if change in viewmodalA it will update the controllerA. Which is fine
Now i push new controllerB onto controllerA.
Now my question is ,i want to connect the viewModalA with the controllerB.
So that ConttollerA and ControllerB should have one source of truth.
Does anyboday can help me
I think the better option is to ditch viewModels and use repositories for data management, you can just observe xRepository in controllerA and B.
@@Kaanozkaya24 can u share me some article or link
@@Kaanozkaya24 does the repository will be singleton or i need to do the dependency injection
@@MuhammadUsman-xi7ou It should be singleton, so you won't have to inject it.
Sometimes dumb is good LOL Great tutorial!
In this case... absolutely, lol.
are you planning on making a course for networking?
I don't have a course dedicated to just networking. However we utilize networking in my courses.
Finally!
I have to change so much stuff now :( lol thank you!
You're welcome... I think, lol
visitor: what is mvvm?
Sean: make your code look stupid
5:44 connecting view to view model
Just a suggestion. Slow down a bit. Let the viewer digest what say and see the screen content.
thanks
You're welcome!
View is dumb LOL great explanation 👏
I try to explain things in the simplest and most memorable way. I think that one works 😀
I don't know why are they calling this patterns? You create reusable views (image, hstack and so on), it is natural that you do that. And then you call a function that i grabbing something from api. It is natural that you will put in some api calls in other file/class. Why don't they make this simple and always say, separate views in to small files, put in api cals in some class and make them observable? This mvvm and big names ... I dont get this. I would call it SWIFT BEST PRACTICES. And then you read it and follow it.
Harris Sarah Harris Steven Johnson Scott
So MVVM is just Java practice. Bunch of injections
If you are following along running Swift 6 you will get a warning if you do not refer to 'self.' for closures. E.g. the function 'getAppetizers' change 'alertItem = AlertContext.invalidData' to 'self.alertItem = AlertContext.invalidData'
can anybody please tell me that why don't we put $ with viewModel.isLoading in our AppetizerListView? we put $ on viewModel.alertItem but not with isLoading and appetisers in same AppetizerListView! this is very confusing for me!
If you enjoy my teaching/presentation style I started creating my own iOS development courses at seanallen.teachable.com. You can watch the first ~10% of each course as a free preview to get a feel for them.
So, is the ViewModel the same thing as the Controller in MVC?
If yes, what is the differencebetween MVC and MVVM then?