Lecture 3: Reactive UI + Protocols + Layout

The third of the lectures given to Stanford students in Spring quarter of 2020 demonstrates the mechanisms supporting SwiftUI’s reactive UI paradigm by enhancing Memorize to flip the cards over when they are tapped. Protocols, an important Swift language feature, are covered in detail as is some of the API for laying out Views, including the “Stacks”, View modifiers and GeometryReader. A fundamental principle of MVVM in SwiftUI is the reactive, declarative approach to building UIs. The View of our MVVM is always automatically reflecting the state in our Model, creating a single source of “truth” for the heart of the application’s logic and storage. Added to that, we formalize the concept of capturing the user’s “intent” to do something and using that to change the Model appropriately. Going back to our demo, we apply this to our Memorize application by using @ObservedObject and @Published to make tap gestures cause cards to flip over. After that, we dive back into an exploration of a very important functional-/protocol-oriented-programming topic: protocols. Finally, we go over many of the ways we can lay out the graphical elements of our UI on screen, from HStack, VStack and ZStack, alignment and spacing, and GeometryReader, a mechanism for adjusting our appearance to the space allocated to us in the UI.