Stanford CS193p: MVVM and Swift Types

Aug 19, 2024

Stanford CS193p - Lecture 2 Notes

Introduction

  • Lecture 2 of Stanford CS193p (Spring 2020)
  • Topics covered:
    • MVVM (Model-View-ViewModel) design pattern
    • Swift type system

MVVM Overview

  • MVVM is a design paradigm for organizing code in SwiftUI.

    • Necessary for SwiftUI development.
    • Different from MVC (Model-View-Controller used in UIKit).
  • Model:

    • The backend of the app, UI independent.
    • Encapsulates data and logic (e.g., card data and matching logic).
    • Always considered the truth for the app's data.
  • View:

    • Reflects the Model.
    • Stateless: Does not hold state, only displays the current state of the Model.
    • Declarative: Changes only when the Model changes.
  • ViewModel:

    • Binds the View to the Model.
    • Interprets Model data for the View.
    • Notifies the View of changes in the Model.

Key Concepts of MVVM

  1. Data Flow:

    • Data flows from the Model to the View.
    • The View displays the current state of the Model.
  2. Reactive Programming:

    • The View updates automatically when the Model changes.
    • ViewModel notices changes and publishes updates.
  3. User Intent:

    • The View communicates user actions to the ViewModel, which modifies the Model accordingly.
    • Example: User choosing a card in a memory game.

Swift Type System

  • Important types in Swift:
    • Struct: Value type, gets a free initializer.
    • Class: Reference type, needs an explicit initializer.
    • Protocol: A blueprint of methods, properties, and other requirements.
    • Generics: Types that don't strictly define what the data type must be.
    • Functions: Can be treated as types.

Struct vs Class

  • Struct:

    • Value type, copied when passed around.
    • No inheritance.
    • Free initializer for all properties.
  • Class:

    • Reference type, passed by reference.
    • Supports single inheritance.
    • Requires explicit initializers for properties.

Generics and Functions

  • Generics allow functions to accept any data type.
  • Functions can be passed as parameters to other functions, supporting functional programming principles.

Practical Application in demo

  • Implementing MVVM for a memory game application using SwiftUI.
  • Card model and ViewModel examples.
  • Use of @State and ObservableObject to handle state changes in SwiftUI.

Conclusion

  • Homework Assignment: Reproduce the demo from the lecture.
    • Shuffle cards.
    • Implement a random number of card pairs.
  • Encourage students to ask questions on Piazza.