mvvm swiftui in swift

MVVM (Model-View-ViewModel) is a design pattern that separates the data (Model) from the UI (View), using a middleman (ViewModel) to communicate between them. In Swift, you can create a basic MVVM structure in SwiftUI by following these simple steps:

  1. Create a ViewModel class or struct that will hold your app's state and logic. This class should also be responsible for fetching data from APIs or databases. It should conform to ObservableObject protocol, and expose an @Published property to notify the View of any changes in the data.
main.swift
import Combine

class ViewModel: ObservableObject {
   @Published var data: [String] = []
   var cancellable: AnyCancellable?

   func fetchData() {
      cancellable = URLSession.shared.dataTaskPublisher(for: URL(string: "https://yourapi.com/data")!)
         .map { $0.data }
         .decode(type: [String].self, decoder: JSONDecoder())
         .replaceError(with: [])
         .assign(to: \.data, on: self)
   }
}
419 chars
15 lines
  1. Create a View that will display the data from the ViewModel. This is your UI layer. Declare all your UI components here, and set their values based on the data in the ViewModel. Use the @ObservedObject property wrapper to get changes from the ViewModel.
main.swift
struct MyView: View {
   @ObservedObject var viewModel = ViewModel()

   var body: some View {
      NavigationView {
         List(viewModel.data, id: \.self) { datum in
            Text(datum)
         }
      }
      .onAppear {
         viewModel.fetchData()
      }
   }
}
278 chars
15 lines
  1. Finally, add the View to your app's main view hierarchy.
main.swift
@main
struct MyApp: App {
   var body: some Scene {
      WindowGroup {
         MyView()
      }
   }
}
105 chars
9 lines

This is a basic outline of how to implement MVVM in SwiftUI. There are many variations and techniques you can use to make it work for your app, but this should give you a good starting point.

related categories

gistlibby LogSnag