ArchitectureMidMCQ
What is MVVM and how does it work in iOS?
Test your knowledge:
Explanation & Code
Answer: MVVM (Model-View-ViewModel) separates business logic from UI. The ViewModel exposes data and actions; the View observes and renders. No direct reference from ViewModel → View.
Model ←→ ViewModel ←→ View
↑
(no UIKit/SwiftUI imports)
Code Example:
// Model
struct Article: Codable {
let title: String
let body: String
}
// ViewModel — no UIKit, no View references
@MainActor
class ArticleViewModel: ObservableObject {
@Published var title: String = ""
@Published var body: String = ""
@Published var isLoading: Bool = false
func load(id: String) async {
isLoading = true
let article = try? await ArticleService.fetch(id: id)
title = article?.title ?? ""
body = article?.body ?? ""
isLoading = false
}
}
// View — only rendering logic
struct ArticleView: View {
@StateObject var viewModel = ArticleViewModel()
var body: some View {
VStack {
if viewModel.isLoading {
ProgressView()
} else {
Text(viewModel.title).font(.title)
Text(viewModel.body)
}
}
.task { await viewModel.load(id: "123") }
}
}
Rate your understanding: