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

Комментарии • 114

  • @Sperius7
    @Sperius7 3 года назад +42

    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!

  • @GrégoryV-b5s
    @GrégoryV-b5s 10 месяцев назад +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  10 месяцев назад

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

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

  • @clayfulgham21
    @clayfulgham21 8 месяцев назад +1

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

    • @seanallen
      @seanallen  8 месяцев назад

      Happy to hear it was helpful!

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

  • @jaylensmith6308
    @jaylensmith6308 2 года назад +1

    Who knew I was passively making a MVVM.

  • @hengideguru
    @hengideguru 3 года назад +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  3 года назад +1

      Glad you enjoyed it, Prajwal.

  • @nadnerb2178
    @nadnerb2178 3 года назад +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.

  • @callmetyler
    @callmetyler 3 года назад +8

    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.

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

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

  • @coolisfoolable
    @coolisfoolable 3 года назад +2

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

  • @Bjorn-EricAbrahamsson
    @Bjorn-EricAbrahamsson Год назад

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

  • @PhilipJMayo
    @PhilipJMayo 3 месяца назад

    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?

  • @ankitsoni3388
    @ankitsoni3388 2 года назад +1

    Thanks brother, it was simple and super crisp.

  • @OperaFanDallas
    @OperaFanDallas 2 года назад +1

    You are awesome!!! Love your style.

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

  • @NishantNarola
    @NishantNarola 3 года назад

    great example for starter atleast..keep it up..one suggestion instead of calling getAppetizers function in onAppear, call in initializer in view model class

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

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

  • @justinpelletier441
    @justinpelletier441 7 месяцев назад

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

  • @gamebazar6453
    @gamebazar6453 6 месяцев назад

    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?

  • @megustaeljamonelchorizoylo560
    @megustaeljamonelchorizoylo560 3 года назад

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

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

  • @GowthamRaj_Pampana
    @GowthamRaj_Pampana 2 года назад

    Excellent @sean short and straight

  • @SteemeX
    @SteemeX 3 года назад

    Sean, thank you! This vid was very helpful

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

  • @luciovieirajunior9299
    @luciovieirajunior9299 3 года назад

    Thank you!!! Good example and clear explanation

  • @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 Год назад

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

  • @ElitePanCake645
    @ElitePanCake645 3 года назад

    Beautiful explanation. Thank you. Keep it up.

  • @josephlyons3393
    @josephlyons3393 3 года назад

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

  • @mahinur_rahman
    @mahinur_rahman Год назад

    Simplest explanation! thanks a lot

  • @Batmanyank
    @Batmanyank 3 года назад

    Thanks Sean. As always great tutorial. 🙌

  • @josephalbanese4859
    @josephalbanese4859 7 месяцев назад +1

    TY Sean! Great video.

    • @seanallen
      @seanallen  7 месяцев назад

      Glad you enjoyed it

  • @marekdado4282
    @marekdado4282 3 года назад

    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 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 3 года назад

      I have the same question... still unclear after reading several articles.

  • @dimiutube
    @dimiutube 3 года назад

    Good and clear explanation! Thanks for that! 😃

  • @osmansuliman5226
    @osmansuliman5226 3 года назад

    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

  • @ongunpalaoglu3688
    @ongunpalaoglu3688 3 года назад

    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?

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

  • @megustaeljamonelchorizoylo560
    @megustaeljamonelchorizoylo560 3 года назад

    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

  • @jlambert12013
    @jlambert12013 Год назад

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

  • @Jisam99
    @Jisam99 3 года назад

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

  • @daniilsurnin795
    @daniilsurnin795 3 года назад

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

  • @umutkayatuz9963
    @umutkayatuz9963 2 года назад

    Should network calls not be placed in the model?

  • @parthbarot-nc8mr
    @parthbarot-nc8mr 13 дней назад

    Please Make Video for how to write Unit Tests

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

  • @co48756
    @co48756 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 3 года назад

      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.

  • @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 Год назад

      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 Год назад

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

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

  • @zainhaider6628
    @zainhaider6628 2 года назад

    That was a great video. Thanks.

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

  • @slimKhan
    @slimKhan 3 года назад

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

  • @kenanganmasakecilku3816
    @kenanganmasakecilku3816 3 года назад

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

  • @rachitsharma8829
    @rachitsharma8829 2 года назад

    Why we are using Final before Class Name ?
    to get rid of class could not be inherited

    • @seanallen
      @seanallen  2 года назад

      When you add "final" before a class, that means that it cannot be sub-classed.

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

  • @glennadams7047
    @glennadams7047 3 года назад +1

    Sometimes dumb is good LOL Great tutorial!

    • @seanallen
      @seanallen  3 года назад

      In this case... absolutely, lol.

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

  • @TheAhmadReza
    @TheAhmadReza 3 года назад

    Finally!

  • @tankstechtutorials5721
    @tankstechtutorials5721 3 года назад +1

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

    • @seanallen
      @seanallen  3 года назад

      You're welcome... I think, lol

  • @mourbatsalim4830
    @mourbatsalim4830 2 года назад

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

  • @andres121231
    @andres121231 8 месяцев назад

    5:44 connecting view to view model

  • @wayneosaur
    @wayneosaur Год назад

    Just a suggestion. Slow down a bit. Let the viewer digest what say and see the screen content.

  • @MrBeavis2014
    @MrBeavis2014 2 года назад +1

    thanks

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

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

  • @MatthewMartin-u9l
    @MatthewMartin-u9l 2 месяца назад

    Harris Sarah Harris Steven Johnson Scott

  • @ChibuikeHenrychime
    @ChibuikeHenrychime 10 месяцев назад

    So MVVM is just Java practice. Bunch of injections

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

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

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