avatarMichael Long

Summary

The provided content discusses the intricacies of SwiftUI, emphasizing the differences between SwiftUI views and traditional UIKit views, the importance of understanding state and view graph dynamics, and the implications for performance and architecture in SwiftUI applications.

Abstract

The article delves into the nuances of SwiftUI, a declarative framework for building user interfaces across Apple platforms. It challenges the preconceived notions of iOS developers by clarifying that SwiftUI views are not equivalent to UIKit views but are instead lightweight descriptions of the desired interface. The author explains the state-driven nature of SwiftUI, illustrating how changes in state trigger updates to the view graph, leading to interface re-rendering. The article also highlights the ephemeral nature of SwiftUI views, the potential performance pitfalls of improper view model handling, and the asynchronous nature of view updates. It introduces the concept of local state management using @State and the newer @StateObject property wrapper, which helps manage view model lifecycles more effectively. The author advocates for a paradigm shift in how developers approach SwiftUI application architecture, moving away from UIKit-centric patterns and embracing the declarative and protocol-oriented design of SwiftUI.

Opinions

  • The author suggests that traditional UIKit development patterns are not directly applicable to SwiftUI and may lead to misunderstandings and inefficient code.
  • There is a strong emphasis on the importance of keeping SwiftUI views lightweight and free from heavy computations during initialization and in their body properties.
  • The article criticizes the practice of attaching class-based view models to views using @ObservedObject, proposing @StateObject as a more suitable alternative for managing object lifecycles in SwiftUI.
  • The author points out that SwiftUI's asynchronous update cycle can lead to unexpected behavior if developers assume synchronous updates similar to UIKit's view lifecycle.
  • The article argues for a distributed approach to state management, advocating for keeping state as localized as possible within the view hierarchy to enhance performance and maintainability.
  • The author encourages developers to engage with the SwiftUI framework on its own terms, leveraging its unique features and design principles rather than trying to force UIKit paradigms onto it.

Deep Inside Views, State and Performance in SwiftUI

Or why those words may not mean what you think they mean.

Quite a few people have written articles on SwiftUI, SwiftUI state management, and on SwiftUI application architecture. And quite a few of those articles were written by people eager to take their favorite iOS application architecture and port it over to SwiftUI.

Hence we’ve had articles telling us how to use MVVM with SwiftUI. Or VIPER. Or Clean. Or those that insist that we need to impose a React/Redux architecture on top of it.

But most of them have a problem.

You see, many of the architectures and methodologies that we’re attempting to inflict on SwiftUI were constructed and honed on applications built with UIKit and that relied on UIKit behaviors. Or worse, they’re architectures designed for other platforms and languages, like JavaScript and React.

And the problem is… SwiftUI is not UIKit.

It doesn’t work the same, and it most definitely doesn’t behave the same.

This article will explore some of the mechanisms behind SwiftUI, and why even the words that we’re using to describe our application and its structure don’t mean what we think they mean.

And why those misunderstandings can lead to performance problems, unexpected behavior, and even fatal errors in our applications.

The Code

Before we get started, I want to make it clear that the following conclusions are based on facts obtained from debugging, instrumenting, profiling, and logging actual SwiftUI applications.

The demonstration code in this article comes from a basic SwiftUI Master/Detail app to which I added a common Model-View-ViewModel architecture. I strongly suggest you download and run the code, interact with the program, and watch the logs as you do so.

This article is long, but a good portion of that length comes from the inclusion of some of that demonstration code and the resulting logs so you can better track the events unfolding as they occur and how those events support the article’s conclusions.

Let’s get started.

There is no View

If you’ve been an iOS developer for any length of time you have UIView and UIViewController baked into your brain.

You understand that views and view controllers are reference types and you understand UIKit’s rather extensive class heirarchy, from NSObject on up.

You understand how view controllers manage views, how they persist in the navigation stack, and all of the UIViewController lifecycle events. And you understand how views are constructed and added to subviews which are added to subviews and how they persist and are managed throughout the window-view-tree.

Unfortunately, it’s this baked-in, ingrained knowledge of how UIKit-based development works that’s actually detrimental to understanding SwiftUI.

Apple didn’t help much in this regard, as SwiftUI’s developers decided in their infinite wisdom to tell you that everything was a “View”. You make views of type View. Your view body returns some View. Even view modifiers return views.

But View is a term that makes long-time iOS developers think one thing when in actuality it’s something very, very, very different.

UIKit is an imperative framework. We build our interface elements piece by piece, one element at a time, and then we wire everything together as best we can and shuffle data back and forth as needed.

SwiftUI, on the other hand, is a declarative framework. We use it to describe the user interface we want and then let SwiftUI build that interface for us based on our description.

So please keep in mind that a SwiftUI View is not the resulting user interface view. It may not even end up being a view at all. A SwiftUI View is just a struct that contains a simple description of what we want our user interface to look like when it’s created and when it’s rendered.

A view may also have the ability to describe how we’re going to want that interface to eventually behave when the user interacts with it. Like when they tap a button.

And that’s it. SwiftUI views are just definitions.

But old habits die hard. We look at a SwiftUI View, see that it’s a View, and in our heads we start thinking that our view definition is going to persist just like it would if it were a UIView. It won’t.

We think that it’s safe to hang view models and other classes off them like we do with UIViewController. It’s not.

We think we know when our “view” is instantiated, when its body variable is called, and how the interface is constructed from that definition. But we don’t.

And we may even think a view modifier modifies its view… I mean, that’s what it’s called, right? But again, the problem is that in many cases it doesn’t really do that either.

There’s a lot to unpack here, so let’s get started.

So if a View is not a View, then what is it?

SwiftUI is a struct-based, protocol-oriented, Domain-Specific-Language developed to describe user interfaces on Apple devices ranging from iPhones to iPads to Apple Watches to the Apple TV and even the Mac.

In that sense, it’s platform agnostic. We give SwiftUI an idea of what we want, and by and large we let it do what’s appropriate when that code’s run on a specific platform. A Toggle view says we want a switch, but how that switch looks and even how it functions differs from iOS to macOS to the Apple TV.

From an implementation standpoint, it’s important to remember that SwiftUI Views are lightweight value types that exist solely to define our interface.

Every custom view we create has a body variable that, when called, returns another view. The returned view might be a primitive view type native to SwiftUI like Text or Image.

struct ItemDateView: View {
    var date: Date
    var body: some View {
        Text("\(date, formatter: dateFormatter)")
    }
}

Here, the description of ItemDateView’s interface is exceedingly simple. We just want to show the user a date formatted as text. The returned view could also be a container view like a List or VStack that tracks and manages a list of views.

struct DetailContentView: View {
    var model: DetailViewModel
    var body: some View {
        tracker {
            VStack(spacing: 16) {
                ItemDateView(item: model.item)
                DetailStateView()
                DetailBoilerplateView(text: model.boilerplate)
                Spacer()
            }
        }
    }    
}

Here, our DetailContentView is also simple. We just want a vertical stack in which we’ll show the contents of our ItemDateView, a DetailStateView, and a DetailBoilerplateView, plus another primitive Spacer view.

Each one of those three custom views has its own body variable, which when called will again return some primitive view, a container view, or a custom view.

In SwiftUI, we rinse and repeat and combine all of these views as needed until we’ve finally defined our entire application.

But note that nothing we’ve defined so far has generated a single user interface element.

Key Point #1: A SwiftUI View is not a view. It’s a description of a view.

State and the View Graph

You can’t do much with SwiftUI without also learning that it’s designed from the ground up to be state-driven.

That state can be as simple as a view property. Or it could be a @State variable, or an @Environment variable, or any of several other types provided for us by SwiftUI.

Each piece of state is the Source of Truth for some part of our application.

WWDC19 “Data Flow Through SwiftUI” presentation

When our application is launched, the views we’ve defined are combined with the initial state of the application and together will eventually form a tree-like structure known as the view graph.

This graph defines how our application appears at that specific point in time.

Application Launch

So let’s run our app and examine the process in detail. Most SwiftUI apps start with a ContentView that’s assigned as the root view of our application in our SceneDelegate. Or, in SwiftUI 2.0, in the main App view.

@main
struct AppStateDemo: App {
    var body: some Scene {
        return WindowGroup {
            ContentView()
        }
    }
}

The struct defining ContentView will be instantiated when our application was launched and that particular instance of the view will exist for the lifetime of the entire application (or the lifetime of the scene, in this case).

So let’s say that it’s finally time for our interface to be rendered and presented to the user. To accomplish this, SwiftUI will ask ContentView’s body variable to provide a set of views that describe the interface we want.

Here’s our ContentView.

struct ContentView: View {
    @ObservedObject var master = MasterViewModel()
    var body: some View {
        NavigationView {
            MasterView()
                .environmentObject(master)
        }
    }
}

This looks straightforward enough. But let’s walk thought it.

First it’s obvious that a MasterViewModel was instantiated when the ContentView was created. We’ve also wrapped it in an ObservedObject property wrapper since it’s an ObservableObject. Seems fine so far.

Next, we’ve been told that SwiftUI will call our body variable to determine what we want to build, so, working inside out in order of evaluation, ContentView’s body variable will first instantiate a custom MasterView struct. We then indicate that an instance of our view model should be inserted into the environment for later use downstream using the environmentObject modifier available on MasterView.

The “view” returned by the modifier is handed to the ViewBuilder needed by NavigationView’s initialization function. Our ContentView’s description is now complete, and the body function will return our completely constructed NavigationView.

And that that builds the initial nodes in our view graph.

Easy as pie.

Except this is SwiftUI, and in SwiftUI, nothing is that simple.

First, and I’m going to keep pounding on this, let me again point out that the NavigationView that’s returned by the ContentView body is not a UINavigationController.

It will indeed cause a UINavigationController to be created (at least on iOS), but here it’s just a struct that tells SwiftUI that some form of navigation will be needed when our application is rendered.

And in point of fact, SwiftUI will begin construction of our navigation view hierarchy before it even calls ContentView’s body variable. Which means that it can’t use our definition’s NavigationView as our UINavigationController.

We haven’t even constructed one yet.

In effect, SwiftUI knows that we need a UINavigationController before we even have a chance to tell it what we want a NavigationView! But how is that possible?

Type Inference

The short answer is simple: Type Inference.

A somewhat longer answer is that in SwiftUI a View is a protocol with an associated Body type that’s defined as the result of the body variable.

public protocol View {
    associatedtype Body : View
    @ViewBuilder var body: Self.Body { get }
}

And if we get print the type of ContentView.Body in the debugger we see…

NavigationView<ModifiedContent<MasterView, 
  _EnvironmentKeyWritingModifier<Optional<MasterViewModel>>>>

As such, SwiftUI can use our return types to tell what sort of things we’re going to need even before we ask for them. But how do we know this?

Logging ContentView

Let’s look at a slightly customized version of ContentView.

struct ContentView: View {
    @ObservedObject var master = MasterViewModel()
    let tracker = InstanceTracker("ContentView")
    var body: some View {
        tracker {
            NavigationView {
                MasterView()
                    .environmentObject(master)
            }
        }
    }
}

This version is identical to the one before, except that we added an InstanceTracker class to our view that lets us know when one is instantiated and which also adds a pass-through function that tells us when our view’s body variable is called. Each time a tracker is instantiated it’s given a new tracking number.

And since tracker is deallocated when our view goes out of scope, we can also track the lifecycle of that view.

AppStateDemo.init() #1
AppStateDemo.body #1 {
  MasterViewModel.init() #2
  ContentView.init() #3
}
UINavigationController.initWithRootViewController
ContentView.body #3 {
  MasterView.init() #4
}

If we look at the debugging log with our tracker’s added, we can see when our MasterViewModel was initialized, when our ContentView was initialized, and then, thanks to a symbolic breakpoint in the debugger, we can see that a UINavigationController was constructed using initWithRootViewController.

And that all of that occurred before ContentView.body was called and had a chance to return our NavigationView/MasterView definition.

Now, you could be forgiven for thinking that this is simply how SwiftUI works, and that it will always build a UINavigationController as part of its app launch process, but we can disprove that in a couple of ways. Simply remove the NavigationView from the code, and SwiftUI won’t construct one.

Or we could erase the result of the Body type using AnyView. If we do that we’ll still get a UINavigationController, but it will be built later in the process, after SwiftUI has had a chance to retrieve and inspect ContentView’s set of view definitions.

AppStateDemo.init() #1
AppStateDemo.body #1 {
  MasterViewModel.init() #2
  ContentView.init() #3
}
ContentView.body #3 {
  MasterView.init() #4
}
UINavigationController.initWithRootViewController

The initial root view controller is our old friend UIHostingController, which indicates that SwiftUI builds its view controller hierarchy almost exactly as we did manually in iOS 12 using SceneDelegate.

Keep in mind that SwiftUI has yet to even peek inside MasterView and yet its already begun construction of our navigation stack and user interface.

MasterView

Moving on, our ContentView said we want to show a MasterView, and to do that we now need to call MasterView’s body variable to request its definition.

Here’s MasterView, also fitted out with a tracker and some more debugging code so we can track our progress.

struct MasterView: View {
    @EnvironmentObject var master: MasterViewModel
    let tracker = InstanceTracker("MasterView")
    var body: some View {
        tracker("List(\(master.items.count) items)") {
            List {
                ForEach(master.items) { item in
                    NavigationLink(
                        destination: DetailView(item: item)
                    ) {
                        ItemDateView(date: item.date)
                    }
                }
            }
            .onAppear {
                tracker("MasterView.onAppear")
            }
            .navigationBarTitle(Text("Master"))
            .navigationBarItems(
                trailing: Button(action: { self.master.add() }) {
                    Image(systemName: "plus")
                }
            )
        }
    }
    
}

Note that MasterView contains a List. As of this writing, Lists in SwiftUI on iOS will generate table views to manage them. Particularly, an UpdateCoalescingTableView with our view and its ForEach loop as its data source. (Modified in iOS 16 to create Collection views.)

If we continue our debugging sequence, we’ll see when MasterView’s body is called.

MasterView.body #4 {
  List(0 items)
}

It’s quite apparent from the logs how SwiftUI instantiates a view inside a body variable, then calls its body variable to get another view, and then calls its body variable when it’s time to construct the interface for that view.

In this particular instance we’re done, but in a more complex application the process of instantiating views, evaluating body variables, building nodes, and constructing user interface elements would repeat until we get to the eventual end of our view tree.

And we finally see…

MasterView.onAppear

Key point #2: Interface construction in SwiftUI is an incremental process.

This is especially true in regard to navigation stacks with UIHostingController and lists that have tableviews at their core.

View Hierarchy

Let’s take a quick look at our view hierarchy.

The gray view in the middle is our table view. The view with the “0 items” text is a ListHostingView, which is rendering the contents of that particular cell.

Note that “0 items” shown in this particular example is not a UILabel view and that’s an important point.

Up to now we might have been slowly lulled back into thinking that there’s a direct correspondence between SwiftUI views and UIKit views. After all, our NavigationView generated a UINavigationController, and our List view generated a table view. (At least it did before iOS 16.)

So wouldn’t a Text view also be an UILabel and an Image view be an UIImageView? Again, that would be simple, easy, and… that’s not how SwiftUI rolls.

In SwiftUI, text and images and shapes are composed and rendered directly on one of a hosting view’s UILayers. HStacks and VStacks, similarly, are not UIStackViews, but fundamentally boil down to positioning calculations for the nested “subviews”.

ZStacks are just slightly more complex, in that each layer in a ZStack generates a new layer on the hosting view. Same for the background and overlay modifiers. Just more layers.

Which brings up back around to our first key point: A SwiftUI View is not a view.

And which also reinforces one of Apple’s original key points: SwiftUI views, in many cases, are not views. Unlike in UIKit, adding another view to a view hierarchy doesn’t generate and add another heavy, clunky NSObject-based UIView to the view rendering and responding chain.

Nor does adding additional HStacks and VStacks to a layout add more UIStackViews and tons of more NSLayoutConstraints.

Key Point #3: There isn’t a direct one-to-one correspondence between SwiftUI view definitions and UIKit view instances.

View Modifiers

In SwiftUI Views can be modified in various ways by view modifiers.

Text("Hello World")
   .forgroundColor(.red)
   .font(.title)

But in actuality, a view modifier is just another struct that wraps the parent struct, which wraps the parent struct, etc..

But as I mentioned above, most view modifiers don’t actually modify the view. In fact, and as we’ve seen, there is often no view to modify. So what’s happening?

The short answer is that quite a few of the available view modifiers modify not the view but the environment.

Key Point #4: The current state of the environment is used when it’s time to render our interface.

We want to render of piece of text, so we grab the current font from the environment, and the current foreground color, and we use those values to do our rendering. That’s how, for example, setting the current foregroundColor on a VStack or Group impacts each of the Text values contained within it.

VStack {
    Text("A")
    Text("B")
}
.foregroundColor(.red)

Each text element shown in the above example will be red.

State Change

Now for the fun part. Our application is up and running and the user taps a button that causes our application’s state to change. Or maybe a timer fires or an API finally returned a result. How it occurs doesn’t really matter. The fact that our state changed does.

Key Point #5: When state changes, any view with a direct dependency on that state will be regenerated.

By that I meant the dependent view’s body variable will be called and asked to provide a new definition of what the user interface should now look like based on the new state of the application. In short, it returns a new View.

Note that this one single request can trigger a cascade down that entire branch of the view graph.

In our definition of MasterView, we included MasterViewModel as an @EnvironmentObject, which makes MasterView directly dependent on MasterViewModel. If MasterViewModel changes, then MasterView needs to be rebuilt in order to see what might have changed.

struct MasterView: View {
    @EnvironmentObject var master: MasterViewModel
    var body: some View {
         ...
    }
}

So let’s hit the “plus” button to add a new entry to our list and observe the results.

ContentView.body #3 {
  MasterView.init() #6
}
MasterView.body #6 {
  List(1 items)
}
...

ContentView is also dependent on our MasterViewModel via ObservableObject. So when MasterViewModel changes SwiftUI will once again call view ContentView’s body variable to get a new view definition.

In the body variable ContentView instantiates a new, modified MasterView struct. That will, in turn, eventually cause SwiftUI to call view MasterView’s body once more get that view’s definition.

That would have occurred anyway since, as we’ve mentioned several times, MasterView also has a direct dependency on MasterViewModel.

TableView Updates

MasterView uses a List, and a List is a tableview, and we now have some data to display… so now it’s time for the tableview to reload its data and build some cells from its datasource.

We only have one cell at this point, so let’s see what else has been logged.

...
DetailView.init() #7
DetailViewModel.init() #8
ItemDateView.init() #9
ItemDateView.body #9 {
  2020-08-23 22:36:14 +0000
}
ItemDateView.body #9 {
  2020-08-23 22:36:14 +0000
}
ItemDateView.body #9 {
  2020-08-23 22:36:14 +0000
}
MasterView.deinit() #4

Say what? Note that in constructing our cell an instance of our DetailView was instantiated… along with its associated view model!

I wrote about this at some length in SwiftUI and How NOT to Initialize Bindable Objects. (The title of which should tell you just how long this particular behavior has been around).

The bottom line is that every view in SwiftUI is a struct. Structs must be initialized when created. Our detail view is immediately instantiated and passed to NavigationLink as a parameter when that view is displayed and as such anything we construct during view initialization or as a view property will also be instantiated at the same time.

struct DetailView: View {
    @EnvironmentObject var master: MasterViewModel
    @ObservedObject var model: DetailViewModel
    init(item: Item) {
        self.model = DetailViewModel(item: item)
    }
    let tracker = InstanceTracker("DetailView")
    var body: some View {
        tracker {
            DetailContentView(model: model)
                .padding()
                .navigationBarTitle(Text("Detail"))
                .navigationBarItems( ... )
                .onAppear {
                    print("- DetailView onAppear")
                }
        }
    }
}

As shown above, I instantiated a view model with the item passed in the ForEach loop, but due to the way NavigationLink works, our “lightweight” DetailView will now do a DetailViewModel heap allocation the instant we make a DetailView.

That’s not good.

More to the point, what happens if our list grew to where we had, say, a 1,000 items in it? Well, then we’re going to have a bunch of DetailViewModel objects continually being created and disposed of while we scroll around.

And whether we actually visit that page or not.

What if those models were doing some sort of processing on init? Also not good.

And what happens if this view is regenerated and our view model ends up being replaced when we’re not expecting it? That’s definitely not good. We’ll come back to this point a bit later.

Downstream Changes

Key Point #6: When state changes, views downstream of that direct dependency may be also reinstantiated and regenerated.

Changing our state will ultimately result in new nodes for our view graph, which now represents the new state of the application. SwiftUI will then compare the new definitions against the definitions contained in the previous view graph.

Key Point #7: At any point where the graphs diverge, SwiftUI will update the user interface and the view graph accordingly.

So if a font or color or some text property has changed, SwiftUI will update the appropriate font or color or text and redraw the relevant sections of the interface.

SwiftUI may even animate certain changes to the interface for us. If, say, an item is removed from a List or a VStack, then SwiftUI may animate the items beneath it upwards, closing the gap. Or it may do the opposite if another view is added.

The change might be even more drastic, if, say, a presented view should be shown or dismissed.

Once that’s done our user interface will once again accurately reflect our state, and the nodes in new view graph will replace those in the old view graph, ready for the next event.

The same exact thing happens all over again when we have another state change. And the next change. And the next. The view graph in a SwiftUI-based application is in a constant, never-ending state of flux.

Views are Ephemeral

This brings us to another key point that can not be stressed enough.

Key Point #8: SwiftUI Views are constantly being constructed and evaluated during the lifetime of our application.

Each and every state change can result in part or all of the view graph being reconstructed. Translated, that means your old views are going to get tossed and replaced with new views.

This means that anything attached to one of those views will also go away.

Think about the consequences of that for a moment.

Or better yet, let’s hit our plus button one more time and observe the result.

ContentView.body #3 {
  MasterView.init() #11
}
MasterView.body #11 {
  List 2 items
}
DetailView.init() #12
DetailViewModel.init() #13
ItemDateView.init() #14
ItemDateView.body #14 {
  2020-09-09 00:06:24 +0000
}
ItemDateView.deinit() #9
DetailViewModel.deinit() #8
DetailView.deinit() #7
DetailView.init() #15
DetailViewModel.init() #16
ItemDateView.init() #17
ItemDateView.body #17 {
  2020-09-09 00:06:31 +0000
}
MasterView.deinit() #6

Note our reconstructed MasterView was once again thrown away and rebuilt. Worse, note that our original DetailView and our carefully constructed DetailViewModel for our first data element was also unceremoniously tossed aside in favor of a new one.

Lightweight Views

This leads us to a new pair of rules.

Key Point #9: Don’t do computationally heavy work on view initialization.

SwiftUI views are lightweight structs for a reason. Do NOT burden the view initialization process with heap allocations or do a lot of processing at that point in time.

Further, note that each of our ItemDateView’s body variables were called three times apiece during the construction and display of each List cell.

As I said at the beginning, you don’t really know just when SwiftUI is going to need to access your view’s definition. Or how often it’s going to do so.

So, if you don’t know when a block of code is going to be called, and if you don’t know how often it’s going to be called, should you put critical or data intensive code there?

Especially when doing so can have a significant impact on your application’s performance?

I don’t think so. There’s a time and a place for everything, but view initialization and inside your view’s body variable isn’t that time nor is it the place.

Key Point #10: Don’t do computationally heavy work in your view body either.

Root Dependencies

Note that several of the points we’ve made warrant further consideration.

As should be obvious by now, state change can have a major impact on the view graph, and just how much impact it has largely depends on just where the dependent view exists in the view hierarchy.

WWDC19 “Data Flow Through SwiftUI” presentation

A dependency low or near the edge of the hierarchy will have a small impact on the number of views that need to be regenerated. As a small example, a button that changes its background color when tapped is a small, extremely localized change within the view hierarchy.

Conversely, a dependency located at the root or high in our view hierarchy can cause the entire downstream view graph to be regenerated and the results compared each and every time the dependent state changes. As we just demonstrated in the section on Rebuilding the View Graph.

For best performance, such “root” dependencies should be avoided or minimized if at all possible.

As such, a React/Redux “there can be only one” style of global state management should probably be avoided, as any state change will cause everything dependent on the central data store to be regenerated. Again, basically the entire application view graph.

Key Point #11: Avoid large collections of state data. Keep state localized where possible.

In fact, I wrote about this at some length in a previous article, SwiftUI Microservices.

Note that the last point ends with the phrase “where possible”. While root dependencies should be avoided, they also shouldn’t be feared either. Provided, of course, that you’ve begun following my advice to keep your view initializations and view bodies as lightweight and performant as you can.

It is, after all, how SwiftUI was designed to work.

Asynchronous Updates

Earlier I mentioned that changing state will ultimately result in a new view graph. I choose those words with care, as the key word in that sentence is ultimately.

Key Point #12: User interface updates happen after the state change has occurred during an asynchronous update scheduled for the next run cycle.

I alluded to this earlier, but changing several @Published variables on an ObservableObject will fire several .objectWillChange() events. Those events are aggregated and will eventually — not immediately — trigger a view update cycle on the next RunLoop.

That may be hard to parse without an example, so let’s look at one.

Let’s examine a portion of our MasterView model, which has a few Combine sinks defined in our init function solely for tracking purposes.

class MasterViewModel: ObservableObject {
    @Published var update1 = 0
    @Published var update2 = 0
    var cancellable0: AnyCancellable!
    var cancellable1: AnyCancellable!
    var cancellable2: AnyCancellable!
    init() {
        cancellable0 = objectWillChange.sink { (value) in
            self.tracker.log("Sink 0 recived change notification")
        }
        cancellable1 = $update1.sink { (value) in
            self.tracker.log("Sink 1 recived value = \(value)")
        }
        cancellable2 = $update2.sink { (value) in
            self.tracker.log("Sink 2 recived value = \(value)")
        }
    }
    func update() {
        update1 += 1
        update2 += 1
        update1 += 1
        update2 += 1
    }
    ...

Note the two @Published items: update1 and update2, that we’ll trigger later on from the DetailView by calling the update function from within a Button press. We saw a version of DetailView earlier, now here’s the collapsed code from inside of the navigation bar button.

    .navigationBarItems(
        trailing: Button(action: {
            DispatchQueue.main.async {
                self.tracker.log("\n### Begin Update Cycle\n")
            }
            self.tracker.log("\n### Begin Update")
            self.master.update()
            self.tracker.log("### End Update\n")
        }) {
            Text("Update")
        }
    )

Notice the async event logging function we throw onto the stack at the beginning of the button action.

We’ll now subscribe to the same view model changes in our MasterView using onReceive.

    var body: some View {
        tracker("List \(master.items.count) items") {
            List {
                ...
            }
            .onReceive(master.objectWillChange) { () in
                tracker.log("MasterView Changed")
            }
            .onReceive(master.$update1) { count in
                tracker.log("MasterView Update 1 Received \(count)")
            }
            .onReceive(master.$update2) { count in
                tracker.log("MasterView Update 2 Received \(count)")
            }
            ...
       }
    }

Now we’re set. Let’s tap on the first item in our list and go to the DetailView.

DetailView.body #12 {
  DetailContentView.init() #18
}
DetailContentView.body #18 {
  ItemDateView.init() #19
  DetailStateView.init() #20
  DetailBoilerplateView.init() #21
}
ItemDateView.body #19 {
  2020-09-09 00:06:24 +0000
}
DetailStateView.body #20 {
  C3901189-FC7F-444C-A17F-C4C1781954CE
}
DetailBoilerplateView.body #21 {
  You're viewing model #13.
}
DetailView onAppear

Straightforward enough. Our DetailView displayed a DetailContentView, which displayed the three elements we illustrated back in the beginning of this article. Just for the record, note that we’re displaying information from DetailViewModel instance #13.

Now let’s press that Update button and look at the log file generated when we actually call our update function. Here’s the first part…

### Begin Update
Sink 0 recived change notification
Sink 1 recived value = 1
Sink 0 recived change notification
Sink 2 recived value = 1
Sink 0 recived change notification
Sink 1 recived value = 2
Sink 0 recived change notification
Sink 2 recived value = 2
### End Update
MasterView Changed
MasterView Update 1 Received 1
MasterView Changed
MasterView Update 2 Received 1
MasterView Changed
MasterView Update 1 Received 2
MasterView Changed
MasterView Update 2 Received 2
### Begin Update Cycle
...

Note that we updated each of our published items twice in the update function, and that we see our sink update notifications received immediately as we’d expect. (If you’ve used other reactive libraries like RxSwift, then this behavior is expected.) We also see our objectWillChange events sent prior to each, as we’d also expect from Apple’s formal definition of that value. The object will change. Then the object did change.

One minor point I’d like to interject here is that you need to be careful in subscribing to an ObservableObject’s objectWillChange publisher. As the log shows, if you do this you’re going to be receiving events for each and every change to each and every published value.

Moving on, note that our view’s onReceive change and data update notifications are received well after we’ve exited the update function (message logged at the end of our button handler).

If we examine the call stack, we’d see that the same button gesture handling event that called our button press handler will in turn forward the appropriate events to our view receivers. This happens before the next update cycle occurs.

Speaking of which, we next see the update cycle message we placed on the main event queue. Note that the following update cycle occurs after our asynchronous event is logged, which in turn indicates that update cycles are asynchronous events that are kicked off the main run loop. (Which debugging confirms.)

So lets examine that update cycle…

Rebuilding the View Graph

I’m including the remainder of the entire log here, just so you can see what cataclysmic forces our update cycle triggered.

...
// BUILDING THE VISIBLE DETAIL VIEW
DetailView.body #12 {
  DetailContentView.init() #22
}
DetailContentView.deinit() #18
DetailContentView.body #22 {
  ItemDateView.init() #23
  DetailStateView.init() #24
  DetailBoilerplateView.init() #25
}
ItemDateView.deinit() #19
DetailStateView.deinit() #20
DetailBoilerplateView.deinit() #21
ItemDateView.body #23 {
  2020-09-09 00:35:14 +0000
}
DetailStateView.body #24 {
  09E1696F-9C5B-441E-8CDA-7C499439E78B
}
DetailBoilerplateView.body #25 {
  You're viewing model #13.
}
// REBUILDING MASTER VIEW
ContentView.body #3 {
  MasterView.init() #26
}
MasterView.body #26 {
  List 2 items
}
/// REBUILDING MASTER VIEW LIST / TABLEVIEW CELLS
DetailView.init() #27
DetailViewModel.init() #28
ItemDateView.init() #29
ItemDateView.body #29 {
  2020-09-09 00:35:15 +0000
}
DetailView.init() #30
DetailViewModel.init() #31
ItemDateView.init() #32
ItemDateView.body #32 {
  2020-09-09 00:35:14 +0000
}
MasterView.onAppear // BUG!!!
MasterView.deinit() #11
ItemDateView.deinit() #14
ItemDateView.deinit() #17
DetailViewModel.deinit() #16
DetailView.deinit() #15
// REBUILDING OUR VISIBLE DETAIL VIEW
DetailView.body #30 {
  DetailContentView.init() #33
}
DetailContentView.deinit() #22
DetailContentView.body #33 {
  ItemDateView.init() #34
  DetailStateView.init() #35
  DetailBoilerplateView.init() #36
}
ItemDateView.deinit() #23
DetailStateView.deinit() #24
DetailBoilerplateView.deinit() #25
ItemDateView.body #34 {
  2020-09-09 00:35:14 +0000
}
DetailStateView.body #35 {
  09E1696F-9C5B-441E-8CDA-7C499439E78B
}
DetailBoilerplateView.body #36 {
  You're viewing model #31.
}

First, our currently visible DetailView was regenerated. Then, and as we’ve seen before, anything dependent on MasterViewModel was rebuilt, including the visible elements of our tableview.

And then our DetailView was called again to display our new information.

Only now it’s a different DetailView. With a different DetailViewModel!

Remember back when I mentioned that we were displaying data from DetailViewModel instance #13? Well, now we’re displaying data from DetailView #30 and DetailViewModel instance #31.

SwiftUI, in rebuilding the tableview, rebuilt our first tableview cell, which instantiated a new DetailView, which instantiated a new DetailViewModel. It then handed off the new view to the hosting controller for the detail screen, and we’re now seeing results from that view and that view model.

Our “view” that was defining and managing our DetailView screen has been replaced.

And that’s the one of the reasons why hanging class-based view models off your views using @ObservedObject is problematic.

If you’re not exceedingly careful, they can and will be killed when you least expect them to be killed. Along with any internal state or data they might have contained.

Your views are not your views.

Local State

Let’s cherry pick something else interesting from the last log.

...
DetailStateView.body #24 {
  09E1696F-9C5B-441E-8CDA-7C499439E78B
}
...
DetailStateView.body #35 {
  09E1696F-9C5B-441E-8CDA-7C499439E78B
}
...

And here’s the corresponding DetailStateView.

struct DetailStateView: View {
    @State var uuid = UUID()
    let tracker = InstanceTracker("DetailStateView")
    var body: some View {
        tracker("\(uuid)") {
            Text("\(uuid)")
                .font(.footnote)
                .foregroundColor(.secondary)
        }
    }
}

Note that our state variable persisted across view instances when the view graph was updated, keeping the same 09E1xxx UUID number.

So why did @State persist but our ObservedObject did not?

Primarily because SwiftUI is managing the storage for @State. As long as it can make sense of the view graph when diffing the new state against the old state, it will do its best to track state variables and make sure they’re constant across instantiations.

On the other hand, objects attached to @ObservedObject are NOT managed by SwiftUI and it’s up to the application to manage their storage and references to them.

All of which makes using @ObservedObject problematic. When do you assign values to them? How do you manage references? How do you keep update cycles from taking down your entire world?

Welcome StateObject

In SwiftUI 2.0 Apple provided a new property wrapper designed to address some of these issues: @StateObject. Let’s look at an example and see how it solves some of our problems with a slightly redesigned DetailView.

struct DetailView: View {
    @StateObject var model: DetailViewModel
    @EnvironmentObject var master: MasterViewModel
//    init(item: Item) {
//        self.model = DetailViewModel(item: item)
//    }

We replace our @ObservedObject with @StateObject and we now pass our view model directly into it via our navigation link.

    NavigationLink(
        destination: DetailView(model: DetailViewModel(item: item))
    ) {
        ItemDateView(item: item)
    }

Looking at the code, one would certainly be justified in asking just how this solves our performance issues. Are we not once more simply instantiating an instance of a view model each and every time we display a new cell in our list?

Actually, we’re not. Let’s look at the initializer for @StateObject.

@inlinable public init(wrappedValue thunk: @autoclosure @escaping () -> ObjectType)

The wrappedValue is actually encased in an @autoclosure and that closure isn’t called until something tries to access the wrapped value. At that point in time our DetailViewModel will be instantiated using the captured item value.

Here’s a log after adding one item.

MasterView Changed
MasterView.body #3 {
  List 1 items
}
DetailView.init() #6
ItemDateView.init() #7
ItemDateView.body #7 {
  2020-09-09 22:23:48 +0000
}

Note that we instantiated a DetailView, but not a DetailViewModel. Let’s now navigate to that page.

DetailViewModel.init() #8
DetailView.body #6 {
  DetailContentView.init() #9
}
DetailContentView.body #9 {
  ItemDateView.init() #10
  DetailStateView.init() #11
  DetailBoilerplateView.init() #12
}
ItemDateView.body #10 {
  2020-09-09 22:23:48 +0000
}
DetailStateView.body #11 {
  4C61F292-8A47-480C-BFCF-92591AD49928
}
DetailBoilerplateView.body #12 {
  You're viewing model #8.
}
DetailView.onAppear

Now we see our DetailViewModel instantiated, along with our familiar update cycle. Interestingly, if we navigate back to the main list, and then once again tap on our single list item, SwiftUI will create a brand new DetailViewModel.

That makes sense if you stop to think about it, as that entire screen went out of scope when we left it, which eliminated any managed storage associated with that portion of the view graph.

There are still several drawbacks to @StateObject, one being that we’ve now exposed our view model to our caller, and the second that while we’re not creating an entire object instance for each and every item in our list, we’re still creating a closure for each, and that’s still a reference type.

If either of those issues is a concern, one could simply wrap the destination view as follows:

struct WrappedDetailView: View {
    let item: Item
    var body: some View {
        return DetailView(model: DetailViewModel(item: item))
    }
}

And of course, using @StateObject means that your minimum deployment target on iOS is now iOS 14.

Completion Block

It took awhile to get here and, in a way, we’ve only just started on our SwiftUI journey.

But now you should have a much better understanding of just what’s going on in your SwiftUI application, where performance bottlenecks could occur, and where potential bugs may lie in wait, ready to take down your entire application.

Perhaps more to the point, you’ve seen first hand how SwiftUI can and will manipulate the views on which your application is based. And what happens if you assume that they persist like our old friend, the UIView.

I’ve spent a good portion of this article telling you what not to do.

  • Don’t assume views persist.
  • Don’t do heavy lifting during view initialization and in your view bodies.
  • Don’t assume you know when your views will be created.
  • Don’t assume you know just when your view bodies will be called.
  • Don’t assume you know just how often your view bodies will be called.
  • Avoid @ObservedObject.

Then again, you can’t build a great application on what not to do. And I’ve tried to help there as well.

  • Keep views lightweight and performant.
  • Keep state as low in the hierarchy as possible.
  • Use distributed state and micro services where possible.
  • Use @StateObject when needed (and if possible).

More articles are coming on how to properly architect SwiftUI applications that keep all of these principles in mind.

But for now, and if you remember nothing else, please remember this...

Don’t treat SwiftUI like UIKit.

It’s not.

Long form content like this takes a lot of time to produce, so please, hit the like button if you want to see more, and if you have any questions or thoughts on the matter just leave a comment.

Seriously. Medium has changed their promotion and payout algorithms, so clapping and leaving comments makes a HUGE difference. Thanks!

Swiftui
iOS App Development
Programming
Software Development
Recommended from ReadMedium
avatarNiraj Paul (iOS developer over 10+ years)
FlyWeight design pattern

It is one of the structural design patterns.

3 min read