Software Dev

The SwiftUI trigger-value pattern

As noted in Swift with Majid, the trigger-value pattern is becoming a thing in SwiftUI.

👉 Trigger value pattern in SwiftUI

Basically, this pattern lets you “trigger” some user experience when some specified data changes.

In one example, when a list of messages changes, then the app automatically immediately trigger some haptic/sensory feedback. And it only takes one extra line of code.

    .sensoryFeedback(.impact, trigger: messages)

The post gives another example of flashing the scroll indicator in the same manner.

And it goes into making your own custom triggers.

This is cool stuff and such a simple + powerful way to make your app more responsive.

Software Dev

Super summary: Demystify SwiftUI

Whenever I get stuck on a sticky problem in SwiftUI, I keep referring back to this great video from WWDC21 for context.

👉 Demystify SwiftUI

The video provides the bigger picture of how SwiftUI works with great analogies to the real world for better understanding.

I thought I’d give this video the super summary treatment to boil it down the most ideas that you can absorb at a quick glance. Refer to the full video 👆 for more info.

SwiftUI tracks three main concepts on a view

  • Identity
  • Lifetime and state
  • Dependencies 

Identity

Identity is how SwiftUI recognizes distinct elements throughout the view’s lifetime.

Identifiers should be stable and unique; it acts like a key.  Multiple views cannot share the same identifier.

Choosing a good identifier is your opportunity to control the lifetime of your view and data.

Types of identifiers

Explicit identifiers are like a dog name and are set with the id parameter. An explicit id is helpful if you want to refer to the view from other views.

Implied identifiers are an inherent identity based on the view’s structure, represented as if statements and other conditions in SwiftUI.

Lifetime and state

Lifetime tracks an existing view’s data over time. For example: the same cat (per identity) can be awake, asleep, annoyed, hungry, etc. over time.

Whenever identity changes, the state is replaced.

Dependencies

Dependencies are how SwiftUI understands when your UI needs to be updated.

Dependencies are the vars on the view, ie. Binding, State, Environment, ObservableObject, etc.

These data elements combine to create a dependency graph that SwiftUI uses to trigger view updates.

Tip

Inert modifiers are cheap and encouraged over branches (structurally different, separate implied identifier).