Simple MVVM in SwiftUI (with async await network request)
For developers who are too busy to read, I will briefly demonstrate how to develop a SwiftUI app using the MVVM pattern.
After creating a SwiftUI project in Xcode, you will usually get two Swift files, one with the same name as your project and the other one is generally called ContentView (may change over time, but currently it is still called ContentView).
Next, let’s create a View Model for ContentView.
Create a new Swift file and name it ContentViewViewModel, and remember to import SwiftUI at the top. Your code should look like this for now:
1 | import SwiftUI |
Now comes the highlight of the article. Because I want to create a View Model for ContentView instead of other Views, I can use a Swift feature called extension to extend ContentView, so that I can use what I am going to write in ContentView.
1 | import SwiftUI |
Go back to ContentView and rewrite it like this:
1 | import SwiftUI |
Great, we have already implemented the simplest MVVM. However, I am not going to end it here. I want to add the function of network requests to ContentViewViewModel to better meet the actual development needs.
Here, I will use a Mock API to simulate some data, which can be found at https://jsonplaceholder.typicode.com/.
I will use the address https://jsonplaceholder.typicode.com/posts, which returns a structure similar to this:
1 | [ |
I will create the model in ContentViewViewModel, which makes it more convenient. In actual cases, it is recommended to create a separate file to build the model.
1 | struct Post: Decodable, Identifiable { |
Then, let’s write a function for requesting data in ContentViewViewModel, and call it in init()
to achieve automatic request.
1 | import SwiftUI |
Finally, go back to ContentView
1 | import SwiftUI |
Mission accomplished, now you already have some concepts about developing SwiftUI App using MVVM pattern.