SwiftUI - Intro to MVVM | Example Refactor | Model View ViewModel

  Переглядів 87,903

Sean Allen

Sean Allen

2 роки тому

Head to squarespace.com/seanallen 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.com/sh/foh2qojd2n...
If you like my teaching or presentation style, I've started creating my own courses:
seanallen.teachable.com/
Twitter:
/ seanallen_dev
Link to my book - How I Became an iOS Developer:
gumroad.com/l/sean-allen-origin
Hired.com:
hired.com/x/1n01g
Check out my podcast, iOS Dev Discussions:
itunes.apple.com/us/podcast/i...
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/762098803
Donny Wals - Combine:
gumroad.com/a/909014131
Mark Moeyken’s SwiftUI Books:
www.bigmountainstudio.com/swiftui-views-book/fzc51
Learn Advanced Swift Here:
gumroad.com/a/656585843
Ray Wenderlich Books:
store.raywenderlich.com/a/208...
Ray Wenderlich Videos:
store.raywenderlich.com/a/208...
Links to my iOS Dev Setup & iOS Dev Book Recommendations
www.amazon.com/shop/seanallen
#swift #softwaredeveloper #iosdeveloper

КОМЕНТАРІ: 110
@Sperius7
@Sperius7 2 роки тому
I’ve heard several explanations of MVVM, but thinking of the view as being dumb makes perfect sense to me - I finally get it!
@seanallen
@seanallen 2 роки тому
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!
@CodeDropAccount
@CodeDropAccount 2 роки тому
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.
@user-wz2yp2dn4d
@user-wz2yp2dn4d 3 місяці тому
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
@seanallen
@seanallen 3 місяці тому
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 :)
@braydoncoyer174
@braydoncoyer174 2 роки тому
A great example to aid in learning this model. Thanks for sharing!
@stewie2689
@stewie2689 2 роки тому
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.
@clayfulgham21
@clayfulgham21 Місяць тому
This is easily the most helpful video I have seen to explain SWIFTUI MVVM
@seanallen
@seanallen Місяць тому
Happy to hear it was helpful!
@megustaeljamonelchorizoylo560
@megustaeljamonelchorizoylo560 2 роки тому
Great video, explained as it should be! Thank you for sharing your knowledge. Please keep going…
@hengideguru
@hengideguru 2 роки тому
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 ❤️
@seanallen
@seanallen 2 роки тому
Glad you enjoyed it, Prajwal.
@mahinur_rahman
@mahinur_rahman 8 місяців тому
Simplest explanation! thanks a lot
@lukasbro
@lukasbro 2 роки тому
That's exactly what I need, thank you, your videos are always great!
@seanallen
@seanallen 2 роки тому
Happy to help, Lukas
@Batmanyank
@Batmanyank 2 роки тому
Thanks Sean. As always great tutorial. 🙌
@jaylensmith6308
@jaylensmith6308 2 роки тому
Who knew I was passively making a MVVM.
@Bjorn-EricAbrahamsson
@Bjorn-EricAbrahamsson Рік тому
Great video! Really appreciate the "visual learning" stuff.
@ElitePanCake645
@ElitePanCake645 2 роки тому
Beautiful explanation. Thank you. Keep it up.
@luciovieirajunior9299
@luciovieirajunior9299 2 роки тому
Thank you!!! Good example and clear explanation
@dimiutube
@dimiutube 2 роки тому
Good and clear explanation! Thanks for that! 😃
@SteemeX
@SteemeX 2 роки тому
Sean, thank you! This vid was very helpful
@GowthamRaj_Pampana
@GowthamRaj_Pampana 2 роки тому
Excellent @sean short and straight
@callmetyler
@callmetyler 2 роки тому
Something always felt wrong about putting functions in my view structs 😅 Thanks for this clear explanation! :)
@seanallen
@seanallen 2 роки тому
Haha, now you know! Happy to help.
@ankitsoni3388
@ankitsoni3388 Рік тому
Thanks brother, it was simple and super crisp.
@seanallen
@seanallen Рік тому
Glad it helped!
@josephalbanese4859
@josephalbanese4859 15 днів тому
TY Sean! Great video.
@seanallen
@seanallen 15 днів тому
Glad you enjoyed it
@coolisfoolable
@coolisfoolable 2 роки тому
You've helped me getting that darn @published / @observableobjec concept to sink in. Thanks!
@seanallen
@seanallen 2 роки тому
Happy to hear it!
@OperaFanDallas
@OperaFanDallas Рік тому
You are awesome!!! Love your style.
@seanallen
@seanallen Рік тому
Thank you so much!!
@laurapotter6321
@laurapotter6321 2 роки тому
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!!!
@seymenozdes
@seymenozdes 6 місяців тому
This is a good topic. Did you learn anything new about this?
@zainhaider6628
@zainhaider6628 2 роки тому
That was a great video. Thanks.
@NishantNarola
@NishantNarola 2 роки тому
great example for starter atleast..keep it up..one suggestion instead of calling getAppetizers function in onAppear, call in initializer in view model class
@ps1kx
@ps1kx 2 роки тому
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() ?
@python_lhu5993
@python_lhu5993 10 місяців тому
new bee in iOS, but quickly pick it up based on your videos, thanks a lot, no 1 iOS training online
@seanallen
@seanallen 10 місяців тому
Glad you like it!
@DaveJacobseniOS
@DaveJacobseniOS 2 роки тому
Thanks for the tutorial and for sharing the code Sean! Came at the perfect time as I’m getting deeper into SwiftUI👌
@Poroto2107
@Poroto2107 2 роки тому
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.
@justinpelletier441
@justinpelletier441 18 днів тому
Could you do a video breaking down Alerts and how you set it up in this video?
@osmansuliman5226
@osmansuliman5226 2 роки тому
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
@marekdado4282
@marekdado4282 2 роки тому
Hi Sean, what about tutorial about HealthKit integration? For example just simple app that display some health data like blood glucose, insulin delivery etc.
@donathmm3881
@donathmm3881 2 роки тому
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?
@jarodpaulson1730
@jarodpaulson1730 2 роки тому
I have the same question... still unclear after reading several articles.
@casperolsen8147
@casperolsen8147 Рік тому
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?
@seanallen
@seanallen Рік тому
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.
@josephlyons3393
@josephlyons3393 2 роки тому
You mentioned having to use classes because of it persisting state, Do Swift structs not hold state?
@glennadams7047
@glennadams7047 2 роки тому
Sometimes dumb is good LOL Great tutorial!
@seanallen
@seanallen 2 роки тому
In this case... absolutely, lol.
@timoernst
@timoernst Рік тому
So, is the ViewModel the same thing as the Controller in MVC? If yes, what is the differencebetween MVC and MVVM then?
@TheAhmadReza
@TheAhmadReza 2 роки тому
Finally!
@Sokrates8
@Sokrates8 2 роки тому
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?
@ongunpalaoglu3688
@ongunpalaoglu3688 2 роки тому
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?
@megustaeljamonelchorizoylo560
@megustaeljamonelchorizoylo560 2 роки тому
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
@nadnerb2178
@nadnerb2178 2 роки тому
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.
@sabarahuja9527
@sabarahuja9527 2 роки тому
Curious why the use of @stateobject in the view instead of @observedobject?
@Kaanozkaya24
@Kaanozkaya24 2 роки тому
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.
@Jisam99
@Jisam99 2 роки тому
Do you think Native(Swift) Loose its demand due to flutter in future??
@casperolsen8147
@casperolsen8147 Рік тому
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?
@seanallen
@seanallen Рік тому
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.
@kenturnbull9679
@kenturnbull9679 2 роки тому
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?
@Cirnxisjudzj
@Cirnxisjudzj 2 роки тому
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.
@tankstechtutorials5721
@tankstechtutorials5721 2 роки тому
I have to change so much stuff now :( lol thank you!
@seanallen
@seanallen 2 роки тому
You're welcome... I think, lol
@umutkayatuz9963
@umutkayatuz9963 Рік тому
Should network calls not be placed in the model?
@redhotbits
@redhotbits Рік тому
massive viewmodel
@acjazz01
@acjazz01 2 роки тому
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.
@JohnDoe19840
@JohnDoe19840 8 місяців тому
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.
@acjazz01
@acjazz01 8 місяців тому
@@JohnDoe19840 yes I've seen too. It works just for small projects, and is not really mvvm.
@MrBeavis2014
@MrBeavis2014 Рік тому
thanks
@seanallen
@seanallen Рік тому
You're welcome!
@FckYouPlz
@FckYouPlz 2 роки тому
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.
@seanallen
@seanallen 2 роки тому
I've never written anything for Android, so I wouldn't know.
@FckYouPlz
@FckYouPlz 2 роки тому
@@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
@FckYouPlz
@FckYouPlz 2 роки тому
@@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
@Kaanozkaya24
@Kaanozkaya24 2 роки тому
@@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.
@alejmc
@alejmc 2 роки тому
@@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.
@daniilsurnin795
@daniilsurnin795 2 роки тому
Why u don't canceling previous task if you dispatch a new one?
@developer-juice-Khailenno
@developer-juice-Khailenno 2 роки тому
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.
@MuhammadUsman-xi7ou
@MuhammadUsman-xi7ou 2 роки тому
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
@Kaanozkaya24
@Kaanozkaya24 2 роки тому
I think the better option is to ditch viewModels and use repositories for data management, you can just observe xRepository in controllerA and B.
@MuhammadUsman-xi7ou
@MuhammadUsman-xi7ou 2 роки тому
@@Kaanozkaya24 can u share me some article or link
@MuhammadUsman-xi7ou
@MuhammadUsman-xi7ou 2 роки тому
@@Kaanozkaya24 does the repository will be singleton or i need to do the dependency injection
@Kaanozkaya24
@Kaanozkaya24 2 роки тому
@@MuhammadUsman-xi7ou It should be singleton, so you won't have to inject it.
@rachitsharma8829
@rachitsharma8829 Рік тому
Why we are using Final before Class Name ? to get rid of class could not be inherited
@seanallen
@seanallen Рік тому
When you add "final" before a class, that means that it cannot be sub-classed.
@kenanganmasakecilku3816
@kenanganmasakecilku3816 2 роки тому
Please use light theme in xcode, because i have problem with my eyes. 😢😢 Thanks ...
@mourbatsalim4830
@mourbatsalim4830 2 роки тому
visitor: what is mvvm? Sean: make your code look stupid
@andres121231
@andres121231 Місяць тому
5:44 connecting view to view model
@jlambert12013
@jlambert12013 10 місяців тому
I don’t really get VeiwModel vs Controller? Couldn’t we just call the view model the controller?
@TheCocuroci
@TheCocuroci 2 роки тому
Why you used @StateObject instead of @ObservedObject?
@tarun_reddy
@tarun_reddy 2 роки тому
are you planning on making a course for networking?
@seanallen
@seanallen 2 роки тому
I don't have a course dedicated to just networking. However we utilize networking in my courses.
@thomasbraun1616
@thomasbraun1616 2 роки тому
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.
@tarun_reddy
@tarun_reddy 2 роки тому
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
@slimKhan
@slimKhan 2 роки тому
Shouldn't be @ObservedObject instead of @StateObject ??
@vamsi3877
@vamsi3877 2 роки тому
View is dumb LOL great explanation 👏
@seanallen
@seanallen 2 роки тому
I try to explain things in the simplest and most memorable way. I think that one works 😀
@wayneosaur
@wayneosaur 7 місяців тому
Just a suggestion. Slow down a bit. Let the viewer digest what say and see the screen content.
@nikola4628
@nikola4628 2 роки тому
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.
@gofudgeyourselves9024
@gofudgeyourselves9024 2 роки тому
Charlie kauffman fans hit like
@user-gb1sb7zt2t
@user-gb1sb7zt2t 2 місяці тому
So MVVM is just Java practice. Bunch of injections
@haloskycrash
@haloskycrash 9 місяців тому
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'
@sarikapaghdal6150
@sarikapaghdal6150 2 роки тому
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!
@seanallen
@seanallen 2 роки тому
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.
Intro to SwiftData - Model, Container, Fetch, Create, Update & Delete
27:13
BRAWLER MUTATIONS WILL BREAK THE GAME! - Brawl Talk
09:34
Brawl Stars
Переглядів 24 млн
когда одна дома // EVA mash
00:51
EVA mash
Переглядів 1,4 млн
Testcontainers have forever changed the way I write tests
12:11
Dreams of Code
Переглядів 46 тис.
Your App Will Get Rejected | New Privacy Rules - 2024
11:26
Sean Allen
Переглядів 25 тис.
MVVM in 100 Seconds
1:42
Philipp Lackner
Переглядів 137 тис.
MVVM Tutorial for Absolute Beginners with SwiftUI (iOS 2022)
10:36
SwiftUI MVVM Tutorial: Simple Example with ObservableObject
12:43
Logan Koshenka
Переглядів 18 тис.
Swift Dependency Injection - What is it? What are the benefits?
6:58
Why Some Designs Are Impossible to Improve: Quintessence
33:03
Design Theory
Переглядів 20 тис.
MVVM is BAD for SwiftUI - Use MVC Instead! (Yes, MVC)
13:28
Rebeloper - Rebel Developer
Переглядів 3,4 тис.
Самая редкая видеокарта от SONY
13:51
Nitroxsenys
Переглядів 54 тис.
The PA042 SAMSUNG S24 Ultra phone cage turns your phone into a pro camera!
0:24
Changing Replace And Edit Backgrounds New Tech || Photo Eedit NEW3X
0:50
Зачем вы показываете ноутбук в аэропорту?✈️
0:29