State

I loved this year’s WWDC session Data Essentials in SwiftUI.

It’s an example of the Newton’s Method analogy of how we learn. We have a first impression and use that to get closer and closer to the truth. (I think I first saw this description in Massey’s book on Topology.)

Last year I thought I understood how @State worked.

It’s not that I was wrong - it was more that my understanding was incomplete.

The magic of @State is that it takes a property that is a value type contained in a struct and moves the storage outside of that struct. The struct now contains a reference to that property. This allows a button action to mutate that property without mutating the struct. The value type now behaves like a reference type.

This year’s session showed that it’s even more magical than that.

These structs that conform to the View protocol are very lightweight and might be discarded once they are rendered on screen.

Imagine I have a simple struct like this.

struct MyView: View {
  @State var count: Int = 0
  
  var body: some View {
    VStack {
      Text(count.description)
      Button("Tap here"){
        count += 1
      }
    }
  }
}

Suppose the instance of MyView is rendered and discarded. The user now taps the button. count changes and so MyView must be instantiated again so that it can be updated on the screen.

When the MyView instance is discarded, something needs to hold on to the count reference or we’ll start at 0 again.

SwiftUI holds onto it for us and connects this reference to count to the new instance of MyView. It feels as if MyView never went away.

I’ve tried to capture this magic in the following comic which I’ll be including in the update to my book A SwiftUI Kickstart which I’ll be updating for free this summer.

State

I love that our understanding of these notions deepens over time.