Skip to main content

IfLet

The ifLet 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

Parameters:
  • toWrappedState: A writable key path from parent state to a property containing optional child state
  • toWrappedAction: A case path from parent action to a case containing child actions
  • wrapped: A reducer builder closure that describes the child reducer to run when state is non-nil
Returns: A reducer that combines the child reducer with the parent reducer

Special Overload for Alerts

A special overload for alerts and confirmation dialogs that does not require a child reducer, since these states are ephemeral and automatically nil out after actions are sent.

Usage

Basic optional child feature

Sheet presentation with effects

Alerts and confirmation dialogs

Order of Operations

The ifLet operator enforces a specific order:
  1. Child reducer runs first - The child processes the action while its state is still available
  2. Parent reducer runs second - The parent can then modify or nil out child state
This ensures child reducers can always handle their actions before being dismissed.

Automatic Behavior

The ifLet operator provides several automatic features:

1. Effect Cancellation

When child state is set to nil, 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

If ifLet receives a child action when child state is nil, it will emit a runtime warning:
This typically happens when:
  • A parent reducer set child state to nil before the ifLet ran
  • An in-flight effect emitted an action after state became nil
  • An action was sent while state was nil

SwiftUI Integration

Use IfLetStore in SwiftUI to observe and present views conditionally:

See Also

  • Scope - For embedding non-optional child state
  • forEach - For embedding reducers over collections
  • @Presents - Property wrapper for optional presentation state
  • PresentationAction - Action type for presented features