IfLet
TheifLet operator embeds a child reducer in a parent domain that operates on an optional property of parent state. It’s commonly used for modeling features that can be presented and dismissed, such as sheets, popovers, drill-down navigation, and alerts.
Method Signature
toWrappedState: A writable key path from parent state to a property containing optional child statetoWrappedAction: A case path from parent action to a case containing child actionswrapped: A reducer builder closure that describes the child reducer to run when state is non-nil
Special Overload for Alerts
Usage
Basic optional child feature
Sheet presentation with effects
Alerts and confirmation dialogs
Order of Operations
TheifLet operator enforces a specific order:
- Child reducer runs first - The child processes the action while its state is still available
- Parent reducer runs second - The parent can then modify or nil out child state
Automatic Behavior
TheifLet operator provides several automatic features:
1. Effect Cancellation
When child state is set tonil, all child effects are automatically canceled. This prevents memory leaks and ensures long-running effects don’t continue after dismissal.
2. Ephemeral State Cleanup
For alerts and confirmation dialogs (types conforming to_EphemeralState), the state is automatically set to nil after any child action is processed. This matches the typical behavior of alerts that dismiss immediately after interaction.
Runtime Warnings
IfifLet receives a child action when child state is nil, it will emit a runtime warning:
- A parent reducer set child state to
nilbefore the ifLet ran - An in-flight effect emitted an action after state became
nil - An action was sent while state was
nil
SwiftUI Integration
UseIfLetStore in SwiftUI to observe and present views conditionally:
See Also
Scope- For embedding non-optional child stateforEach- For embedding reducers over collections@Presents- Property wrapper for optional presentation statePresentationAction- Action type for presented features