extension View {
/// Use this modifier only for static conditions (conditions that are not expected to change
/// while the view lifecycle is ongoing) as if the conditions are dynamic, the entire enclosing
/// view's identity will change underneath the whole hierarchy and it will reset its state,
/// including navigation links that have been opened
///
/// ### Good usage
///
/// swift /// Text("Review Issues") /// .map { view in /// if (userIsAdmin) { /// view.bold() /// } else { /// view /// } /// } ///
///
/// In this example, the user being admin will never change during the lifecycle of the view
/// so this usage is safe
///
/// ### Bad usage
///
/// swift /// List { }.map { view in /// if !receipt.hasIssues { /// view.swipeActions() /// } else { /// view /// } /// } ///
///
/// In this example, the user could fix the issues during the lifecycle of the view.
/// This will trigger the map and the view will be invalidated, losing its state and dismissing
/// all opened screens
///
@ViewBuilder
func map(@ViewBuilder _ transform: (_ view: Self) -> some View) -> some View {
transform(self)
}
}
Assistant
In SwiftUI, views are value types and their identity is determined by their type and position in the view hierarchy. When you use conditional logic to change the modifiers or structure of a view dynamically (i.e., based on variables that can change during the lifecycle of the view), you can inadvertently change the identity of the view in SwiftUI's eyes. This can lead to unexpected behaviors, such as the loss of state or dismissal of navigation links.
The map function you've provided is a custom view modifier that transforms a view using a closure:
swift
@ViewBuilder
func map(@ViewBuilder _ transform: (_ view: Self) -> some View) -> some View {
transform(self)
}
This function allows you to conditionally apply modifiers or transform the view. However, wrapping your view transformations in such a way can lead to issues if the conditions inside the map closure are dynamic.
Why Static Conditions Are Safe
In the "Good usage" example:
swift
Text("Review Issues")
.map { view in
if (userIsAdmin) {
view.bold()
} else {
view
}
}
Static Condition: userIsAdmin is a condition that doesn't change during the lifecycle of the view.
Consistent View Hierarchy: Since userIsAdmin remains the same, the structure of the view hierarchy doesn't change after the view is first loaded.
Stable Identity: SwiftUI can reliably maintain the state and identity of the view because the hierarchy remains consistent.
Safe State Management: Any state associated with the view (like navigation links or input fields) remains intact.
Why Dynamic Conditions Cause Issues
In the "Bad usage" example:
swift
List { }
.map { view in
if !receipt.hasIssues {
view.swipeActions()
} else {
view
}
}
Dynamic Condition: receipt.hasIssues can change during the lifecycle of the view (e.g., if a user resolves an issue).
Changing View Hierarchy: When receipt.hasIssues changes, the result of the if condition changes, altering the modifiers applied to the view.
Identity Reset: SwiftUI sees the view as a different structure when the condition changes, leading to a new identity.
Loss of State: The view's state resets because SwiftUI replaces the old view with a new one, causing issues like dismissed screens or lost input.
Understanding SwiftUI's View Identity
Value Types: SwiftUI views are structs, meaning every change creates a new instance.
View Hierarchy: SwiftUI uses the structure of your views to manage state. The hierarchy is determined by the types and order of views and modifiers.
Conditional Modifiers: Applying modifiers conditionally introduces different view hierarchies depending on the condition.
State Management: If the view hierarchy changes, SwiftUI may reset the state for that view because it treats it as a new entity.
Best Practices
Use Static Conditions for Modifiers: Only use conditions that won't change during the view's lifecycle when applying modifiers in functions like map.
Avoid Dynamic Conditions in View Modifiers: If a condition can change, applying modifiers based on it can lead to state resets.
Separate Dynamic Content: For dynamic conditions, consider structuring your views to handle state changes without altering the hierarchy. Use @State or @Binding to manage changes within the view.
Alternative Approach for Dynamic Conditions
Instead of using map with dynamic conditions, you can handle changes within the view without altering its identity:
swift
List { }
.swipeActions(edge: .trailing) {
if !receipt.hasIssues {
Button("Action") {
// Perform action
}
}
}
Consistent Hierarchy: The swipeActions modifier is always applied, but the content inside adapts dynamically.
Stable Identity: The view's structure remains the same, so SwiftUI maintains its identity.
Managed State Changes: Changes in receipt.hasIssues only affect the content, not the view's identity.
Summary
The comment warns against using dynamic conditions inside the map function because:
Dynamic conditions can change the view hierarchy during the lifecycle of the view.
Changing the hierarchy alters the view's identity, causing SwiftUI to reset the state.
State resets lead to unintended side effects, such as dismissed navigation links or lost input.
By using only static conditions in the map function (conditions that don't change while the view is active), you ensure that the view hierarchy remains consistent, and SwiftUI can correctly manage the state of your views.
Remember: In SwiftUI, consistency in your view hierarchy is crucial for reliable state management. Avoid introducing conditional modifiers based on dynamic conditions that can change, as this can lead to unexpected behavior and a poor user experience.