Bird
Raised Fist0
iOS Swiftmobile~5 mins

MVVM pattern in iOS Swift

Choose your learning style10 modes available
Introduction

The MVVM pattern helps organize your app code by separating data, UI, and logic. This makes your app easier to build and change.

When you want to keep your UI code simple and clean.
When your app has data that changes and you want the UI to update automatically.
When you want to test your app logic without the UI.
When working in a team where designers and developers work separately.
When building apps that need to be easy to maintain and extend.
Syntax
iOS Swift
class ViewModel {
  var data: String = ""
  func fetchData() {
    // load or update data
  }
}

class ViewController: UIViewController {
  var viewModel = ViewModel()
  override func viewDidLoad() {
    super.viewDidLoad()
    viewModel.fetchData()
    // update UI using viewModel.data
  }
}

The ViewModel holds data and logic.

The ViewController shows UI and talks to ViewModel.

Examples
A simple ViewModel that stores a user name and loads it.
iOS Swift
class UserViewModel {
  var name: String = ""
  func loadUser() {
    name = "Alice"
  }
}
The ViewController uses the ViewModel to get data and update UI.
iOS Swift
class UserViewController: UIViewController {
  var viewModel = UserViewModel()
  override func viewDidLoad() {
    super.viewDidLoad()
    viewModel.loadUser()
    print(viewModel.name) // prints "Alice"
  }
}
Sample App

This app shows a number and a button. When you tap the button, the number increases. The ViewModel holds the number and the ViewController updates the screen.

iOS Swift
import UIKit

class CounterViewModel {
  private(set) var count = 0
  func increment() {
    count += 1
  }
}

class CounterViewController: UIViewController {
  let viewModel = CounterViewModel()
  let label = UILabel()
  let button = UIButton(type: .system)

  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white

    label.text = "Count: 0"
    label.textAlignment = .center
    label.frame = CGRect(x: 50, y: 100, width: 200, height: 50)
    view.addSubview(label)

    button.setTitle("Increment", for: .normal)
    button.frame = CGRect(x: 50, y: 160, width: 200, height: 50)
    button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
    view.addSubview(button)
  }

  @objc func buttonTapped() {
    viewModel.increment()
    label.text = "Count: \(viewModel.count)"
  }
}
OutputSuccess
Important Notes

MVVM helps keep your UI code simple and your data logic separate.

Use private(set) in ViewModel to protect data from outside changes.

ViewController listens to user actions and updates UI using ViewModel data.

Summary

MVVM splits app code into Model, ViewModel, and View (UI).

ViewModel holds data and logic, View shows UI and talks to ViewModel.

This pattern makes apps easier to build, test, and maintain.

Practice

(1/5)
1. What is the main role of the ViewModel in the MVVM pattern?
easy
A. To display the user interface elements
B. To hold data and business logic separate from the UI
C. To store raw data from the database only
D. To handle user input directly without any data processing

Solution

  1. Step 1: Understand MVVM roles

    The ViewModel acts as a middleman between the Model and the View, holding data and logic.
  2. Step 2: Identify ViewModel responsibility

    It keeps data and business logic separate from UI, so the View only handles display.
  3. Final Answer:

    To hold data and business logic separate from the UI -> Option B
  4. Quick Check:

    ViewModel = data + logic [OK]
Hint: ViewModel holds data and logic, not UI [OK]
Common Mistakes:
  • Confusing ViewModel with View
  • Thinking ViewModel handles UI rendering
  • Assuming ViewModel stores raw database data only
2. Which of the following is the correct way to declare a ViewModel property in Swift for binding to a SwiftUI View?
easy
A. @State var viewModel = MyViewModel()
B. @EnvironmentObject var viewModel = MyViewModel()
C. var viewModel = MyViewModel()
D. @ObservedObject var viewModel = MyViewModel()

Solution

  1. Step 1: Identify property wrapper for ViewModel

    In SwiftUI, @ObservedObject is used to observe ViewModel changes.
  2. Step 2: Check other options

    @State is for local state, @EnvironmentObject requires external injection, plain var lacks observation.
  3. Final Answer:

    @ObservedObject var viewModel = MyViewModel() -> Option D
  4. Quick Check:

    ViewModel binding uses @ObservedObject [OK]
Hint: Use @ObservedObject for ViewModel in SwiftUI [OK]
Common Mistakes:
  • Using @State for ViewModel instead of @ObservedObject
  • Forgetting to mark ViewModel as ObservableObject
  • Trying to instantiate ViewModel inside @EnvironmentObject
3. Given the following SwiftUI code snippet, what will be displayed when the button is tapped once?
class CounterViewModel: ObservableObject {
  @Published var count = 0
  func increment() { count += 1 }
}

struct ContentView: View {
  @ObservedObject var viewModel = CounterViewModel()
  var body: some View {
    VStack {
      Text("Count: \(viewModel.count)")
      Button("Tap me") {
        viewModel.increment()
      }
    }
  }
}
medium
A. Count: 0
B. Count: Tap me
C. Count: 1
D. Count: nil

Solution

  1. Step 1: Understand initial state

    The count starts at 0 as declared in ViewModel.
  2. Step 2: Analyze button tap effect

    When tapped, increment() adds 1 to count, updating the published property.
  3. Final Answer:

    Count: 1 -> Option C
  4. Quick Check:

    Button tap increments count to 1 [OK]
Hint: Button tap calls increment, count updates [OK]
Common Mistakes:
  • Assuming count stays 0 after tap
  • Confusing button label with count value
  • Expecting nil instead of initial 0
4. Identify the error in this ViewModel code snippet and how to fix it:
class UserViewModel {
  @Published var username: String = ""
  func updateName(newName: String) {
    username = newName
  }
}
medium
A. Missing ObservableObject conformance; add ': ObservableObject' to class
B. Cannot use @Published on String; change to Int
C. updateName should return String; add return type
D. username should be private; add 'private' keyword

Solution

  1. Step 1: Check @Published usage

    @Published requires the class to conform to ObservableObject to work properly.
  2. Step 2: Fix class declaration

    Add ': ObservableObject' after class name to enable property observation.
  3. Final Answer:

    Missing ObservableObject conformance; add ': ObservableObject' to class -> Option A
  4. Quick Check:

    @Published needs ObservableObject [OK]
Hint: Add ObservableObject to use @Published [OK]
Common Mistakes:
  • Forgetting ObservableObject conformance
  • Thinking @Published works without ObservableObject
  • Changing data type unnecessarily
5. You want to create a SwiftUI app using MVVM where the ViewModel fetches a list of users asynchronously and updates the View. Which approach correctly handles this scenario?
hard
A. Make ViewModel conform to ObservableObject, use @Published for users array, fetch data asynchronously and update @Published property
B. Fetch data directly in the View and update a local @State variable
C. Store users array in the Model only and let View read it directly
D. Use a global variable for users and update it from anywhere

Solution

  1. Step 1: Understand MVVM async data flow

    ViewModel should handle data fetching and update @Published properties to notify View.
  2. Step 2: Evaluate options

    Make ViewModel conform to ObservableObject, use @Published for users array, fetch data asynchronously and update @Published property correctly uses ObservableObject and @Published with async fetch; others break MVVM or cause bad design.
  3. Final Answer:

    Make ViewModel conform to ObservableObject, use @Published for users array, fetch data asynchronously and update @Published property -> Option A
  4. Quick Check:

    Async fetch in ViewModel updates @Published [OK]
Hint: Async fetch in ViewModel updates @Published property [OK]
Common Mistakes:
  • Fetching data in View instead of ViewModel
  • Using global variables for state
  • Letting View read Model data directly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard