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

Поділитися
Вставка
  • Опубліковано 27 тра 2021
  • 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
  • Наука та технологія

КОМЕНТАРІ • 111

  • @Sperius7
    @Sperius7 3 роки тому +41

    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  3 роки тому +8

      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 роки тому +8

    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 5 місяців тому +2

    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  5 місяців тому

      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 :)

  • @clayfulgham21
    @clayfulgham21 4 місяці тому +1

    This is easily the most helpful video I have seen to explain SWIFTUI MVVM

    • @seanallen
      @seanallen  4 місяці тому

      Happy to hear it was helpful!

  • @braydoncoyer174
    @braydoncoyer174 3 роки тому

    A great example to aid in learning this model. Thanks for sharing!

  • @stewie2689
    @stewie2689 3 роки тому

    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.

  • @lukasbro
    @lukasbro 3 роки тому +3

    That's exactly what I need, thank you, your videos are always great!

    • @seanallen
      @seanallen  3 роки тому +1

      Happy to help, Lukas

  • @megustaeljamonelchorizoylo560
    @megustaeljamonelchorizoylo560 2 роки тому

    Great video, explained as it should be! Thank you for sharing your knowledge. Please keep going…

  • @hengideguru
    @hengideguru 2 роки тому +3

    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 роки тому +1

      Glad you enjoyed it, Prajwal.

  • @Bjorn-EricAbrahamsson
    @Bjorn-EricAbrahamsson Рік тому

    Great video! Really appreciate the "visual learning" stuff.

  • @Batmanyank
    @Batmanyank 3 роки тому

    Thanks Sean. As always great tutorial. 🙌

  • @jaylensmith6308
    @jaylensmith6308 2 роки тому +1

    Who knew I was passively making a MVVM.

  • @dimiutube
    @dimiutube 3 роки тому

    Good and clear explanation! Thanks for that! 😃

  • @ElitePanCake645
    @ElitePanCake645 2 роки тому

    Beautiful explanation. Thank you. Keep it up.

  • @SteemeX
    @SteemeX 2 роки тому

    Sean, thank you! This vid was very helpful

  • @luciovieirajunior9299
    @luciovieirajunior9299 2 роки тому

    Thank you!!! Good example and clear explanation

  • @GowthamRaj_Pampana
    @GowthamRaj_Pampana 2 роки тому

    Excellent @sean short and straight

  • @mahinur_rahman
    @mahinur_rahman 11 місяців тому

    Simplest explanation! thanks a lot

  • @ankitsoni3388
    @ankitsoni3388 2 роки тому +1

    Thanks brother, it was simple and super crisp.

  • @DaveJacobseniOS
    @DaveJacobseniOS 3 роки тому

    Thanks for the tutorial and for sharing the code Sean! Came at the perfect time as I’m getting deeper into SwiftUI👌

  • @coolisfoolable
    @coolisfoolable 3 роки тому +2

    You've helped me getting that darn @published / @observableobjec concept to sink in. Thanks!

  • @callmetyler
    @callmetyler 3 роки тому +7

    Something always felt wrong about putting functions in my view structs 😅 Thanks for this clear explanation! :)

    • @seanallen
      @seanallen  3 роки тому

      Haha, now you know! Happy to help.

  • @OperaFanDallas
    @OperaFanDallas Рік тому +1

    You are awesome!!! Love your style.

  • @josephalbanese4859
    @josephalbanese4859 2 місяці тому +1

    TY Sean! Great video.

    • @seanallen
      @seanallen  2 місяці тому

      Glad you enjoyed it

  • @ps1kx
    @ps1kx 3 роки тому +1

    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() ?

  • @zainhaider6628
    @zainhaider6628 2 роки тому

    That was a great video. Thanks.

  • @laurapotter6321
    @laurapotter6321 2 роки тому +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 9 місяців тому

      This is a good topic. Did you learn anything new about this?

  • @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

  • @python_lhu5993
    @python_lhu5993 Рік тому

    new bee in iOS, but quickly pick it up based on your videos, thanks a lot, no 1 iOS training online

  • @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

  • @Poroto2107
    @Poroto2107 3 роки тому +3

    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.

  • @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.

  • @justinpelletier441
    @justinpelletier441 3 місяці тому

    Could you do a video breaking down Alerts and how you set it up in this video?

  • @timoernst
    @timoernst Рік тому +1

    So, is the ViewModel the same thing as the Controller in MVC?
    If yes, what is the differencebetween MVC and MVVM then?

  • @josephlyons3393
    @josephlyons3393 3 роки тому

    You mentioned having to use classes because of it persisting state, Do Swift structs not hold state?

  • @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?

  • @Sokrates8
    @Sokrates8 3 роки тому

    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?

  • @casperolsen8147
    @casperolsen8147 2 роки тому +2

    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  2 роки тому

      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.

  • @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

  • @Jisam99
    @Jisam99 3 роки тому

    Do you think Native(Swift) Loose its demand due to flutter in future??

  • @donathmm3881
    @donathmm3881 3 роки тому +1

    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.

  • @gamebazar6453
    @gamebazar6453 Місяць тому

    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?

  • @umutkayatuz9963
    @umutkayatuz9963 2 роки тому

    Should network calls not be placed in the model?

  • @glennadams7047
    @glennadams7047 3 роки тому +1

    Sometimes dumb is good LOL Great tutorial!

    • @seanallen
      @seanallen  3 роки тому

      In this case... absolutely, lol.

  • @nadnerb2178
    @nadnerb2178 2 роки тому +1

    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.

  • @TheAhmadReza
    @TheAhmadReza 3 роки тому

    Finally!

  • @casperolsen8147
    @casperolsen8147 2 роки тому

    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  2 роки тому

      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 3 роки тому

    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.

  • @sabarahuja9527
    @sabarahuja9527 3 роки тому +3

    Curious why the use of @stateobject in the view instead of @observedobject?

    • @Kaanozkaya24
      @Kaanozkaya24 3 роки тому

      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.

  • @daniilsurnin795
    @daniilsurnin795 2 роки тому

    Why u don't canceling previous task if you dispatch a new one?

  • @tankstechtutorials5721
    @tankstechtutorials5721 3 роки тому +1

    I have to change so much stuff now :( lol thank you!

    • @seanallen
      @seanallen  3 роки тому

      You're welcome... I think, lol

  • @FckYouPlz
    @FckYouPlz 3 роки тому +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  3 роки тому

      I've never written anything for Android, so I wouldn't know.

    • @FckYouPlz
      @FckYouPlz 3 роки тому +1

      @@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 3 роки тому +1

      @@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 3 роки тому

      @@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 3 роки тому

      @@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.

  • @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 10 місяців тому

      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 10 місяців тому

      @@JohnDoe19840 yes I've seen too. It works just for small projects, and is not really mvvm.

  • @redhotbits
    @redhotbits Рік тому

    massive viewmodel

  • @jlambert12013
    @jlambert12013 Рік тому

    I don’t really get VeiwModel vs Controller? Couldn’t we just call the view model the controller?

  • @MuhammadUsman-xi7ou
    @MuhammadUsman-xi7ou 3 роки тому

    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 3 роки тому

      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 3 роки тому

      @@Kaanozkaya24 can u share me some article or link

    • @MuhammadUsman-xi7ou
      @MuhammadUsman-xi7ou 3 роки тому

      @@Kaanozkaya24 does the repository will be singleton or i need to do the dependency injection

    • @Kaanozkaya24
      @Kaanozkaya24 3 роки тому +1

      @@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.

  • @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.

  • @kenanganmasakecilku3816
    @kenanganmasakecilku3816 2 роки тому

    Please use light theme in xcode, because i have problem with my eyes. 😢😢 Thanks ...

  • @andres121231
    @andres121231 3 місяці тому

    5:44 connecting view to view model

  • @tarun_reddy
    @tarun_reddy 3 роки тому

    are you planning on making a course for networking?

    • @seanallen
      @seanallen  3 роки тому

      I don't have a course dedicated to just networking. However we utilize networking in my courses.

  • @MrBeavis2014
    @MrBeavis2014 2 роки тому +1

    thanks

  • @slimKhan
    @slimKhan 3 роки тому

    Shouldn't be @ObservedObject instead of @StateObject ??

  • @mourbatsalim4830
    @mourbatsalim4830 2 роки тому

    visitor: what is mvvm?
    Sean: make your code look stupid

  • @TheCocuroci
    @TheCocuroci 3 роки тому

    Why you used @StateObject instead of @ObservedObject?

  • @thomasbraun1616
    @thomasbraun1616 3 роки тому +1

    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 3 роки тому

      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

  • @vamsi3877
    @vamsi3877 3 роки тому +1

    View is dumb LOL great explanation 👏

    • @seanallen
      @seanallen  3 роки тому +1

      I try to explain things in the simplest and most memorable way. I think that one works 😀

  • @wayneosaur
    @wayneosaur 9 місяців тому

    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 3 роки тому

    Charlie kauffman fans hit like

  • @user-gb1sb7zt2t
    @user-gb1sb7zt2t 5 місяців тому

    So MVVM is just Java practice. Bunch of injections

  • @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!

  • @haloskycrash
    @haloskycrash Рік тому

    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'

  • @seanallen
    @seanallen  3 роки тому

    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.