ViewBuilder y applyIf: el coste oculto de una condición en SwiftUI ViewBuilder and applyIf: the hidden cost of a condition in SwiftUI
Por qué un if dentro de @ViewBuilder cambia la identidad estructural de la vista y reinicia su estado. Why an if inside @ViewBuilder changes the view's structural identity and resets its state.
Hay un helper que aparece una y otra vez en proyectos SwiftUI:
extension View {
@ViewBuilder
func applyIf<Content: View>(
_ condition: Bool,
transform: (Self) -> Content
) -> some View {
if condition {
transform(self)
} else {
self
}
}
}
La intención es buena: aplicar un modificador solo cuando se cumple una condición. Compila, es cómodo y parece inocuo. Pero no lo es del todo.
Importante: El problema no es que
applyIfno compile, sino que cadaifcrea dos ramas con identidad propia. Al alternar la condición, SwiftUI destruye el estado de la vista.
Lo que realmente construye ViewBuilder
@ViewBuilder no es solo azúcar sintáctico para elegir una vista u otra. Es un result builder: transforma el cuerpo de la función en una estructura de tipos.
Cuando usamos el helper de esta forma:
MyView()
.applyIf(isEnabled) {
$0.background(Color.red)
}
el compilador genera algo equivalente a:
_ConditionalContent<Content, Self>
_ConditionalContent es un tipo interno de SwiftUI que representa dos ramas posibles. En el ejemplo, una rama contiene la vista modificada y la otra contiene la vista original:
_ConditionalContent<
ModifiedContent<MyView, _BackgroundStyleModifier<Color>>,
MyView
>
Nota: Lo importante es entender que el
ifno se evalúa como una condición dentro de un mismo modificador: la vista resultante tiene dos identidades estructurales posibles.
Identidad estructural, no solo valores
SwiftUI distingue entre el valor de una vista y su identidad en la jerarquía. La identidad estructural depende del tipo y de la posición de la vista en el árbol. Un if/else dentro de un ViewBuilder crea dos posiciones distintas: la rama verdadera y la falsa.
Cuando condition cambia, SwiftUI no está cambiando el parámetro de un mismo modificador. Está eliminando una rama e insertando la otra. Si hay una animación, el resultado es una transición —por ejemplo, un fade— en lugar de una interpolación entre los dos valores.
Eso también afecta al estado. SwiftUI asocia @State, @StateObject, @FocusState y @GestureState al ciclo de vida y a la identidad de la vista. Si la vista cambia de rama, su almacenamiento desaparece y vuelve a inicializarse.
Con el helper definido arriba, el ejemplo se puede probar directamente en un #Preview:
struct Stateful: View {
@State private var text = ""
var body: some View {
TextField("Name", text: $text)
.textFieldStyle(.roundedBorder)
.padding()
}
}
struct Sample: View {
let isEnabled: Bool
var body: some View {
Stateful()
.applyIf(isEnabled) {
$0.background(Color.red)
}
}
}
struct SamplePreview: View {
@State private var isEnabled = false
var body: some View {
VStack(spacing: 24) {
Sample(isEnabled: isEnabled)
Button {
isEnabled.toggle()
} label: {
Text(isEnabled ? "Disable applyIf" : "Enable applyIf")
.fontWeight(.semibold)
.frame(maxWidth: .infinity)
.padding()
.background(Color.blue)
.foregroundStyle(.white)
.clipShape(RoundedRectangle(cornerRadius: 12))
}
Text("isEnabled: \(isEnabled.description)")
.font(.caption)
.foregroundStyle(.secondary)
}
.padding()
}
}
#Preview {
SamplePreview()
}
Al alternar isEnabled, el TextField pierde el texto que el usuario había escrito. Lo mismo ocurre con un @StateObject que se cree dentro de la vista condicional. No es que SwiftUI borre el estado porque sí: para SwiftUI, la vista ha cambiado de posición en el árbol.
Hay un matiz importante: si el estado vive en un padre que no cambia de identidad, sobrevive. El problema afecta al estado que pertenece a la vista que cambia de rama.
Cómo mantener la identidad
La regla práctica es: si las dos ramas representan la misma vista con una configuración distinta, intenta mantener un único tipo y cambia solo el valor.
Cuando el modificador acepta un valor condicional, es la opción más directa:
MyView()
.background(isEnabled ? Color.red : Color.clear)
MyView()
.frame(width: isEnabled ? 200 : 100)
MyView()
.opacity(isEnabled ? 1 : 0)
También puedes encapsular la condición en un ViewModifier estable:
struct ConditionalBackground: ViewModifier {
let isEnabled: Bool
func body(content: Content) -> some View {
content.background(isEnabled ? Color.red : Color.clear)
}
}
extension View {
func conditionalBackground(_ isEnabled: Bool) -> some View {
modifier(ConditionalBackground(isEnabled: isEnabled))
}
}
Nota: El tipo
ModifiedContent<MyView, ConditionalBackground>no cambia; elBooles solo un parámetro. La identidad se mantiene y el modificador se sigue aplicando siempre.
Cuándo sí usar un if
No se trata de prohibir applyIf o los if en ViewBuilder. Las ramas son la herramienta correcta cuando realmente queremos dos estructuras distintas: mostrar una pantalla de carga o el contenido, un estado vacío o una lista, una vista u otra.
La clave es elegir conscientemente:
- Si quieres cambiar la estructura, usa
if/elsey asume que la identidad cambia. - Si quieres cambiar solo una propiedad de la misma vista, mantén la identidad y pasa el valor al modificador.
- Si el estado debe sobrevivir a un cambio estructural, súbelo a un padre estable o a un modelo que no se destruya.
Conclusión
applyIf es cómodo, pero esconde una decisión de arquitectura: cada if en un ViewBuilder crea dos ramas con identidad propia. Eso reinicia el estado de la vista que cambia de rama.
Antes de añadir un helper condicional, merece la pena preguntarse si las dos ramas son realmente dos vistas distintas o la misma vista con una configuración diferente. Si es lo segundo, mantener el tipo estable es la opción más predecible.
Referencias
There is a helper that keeps showing up in SwiftUI projects:
extension View {
@ViewBuilder
func applyIf<Content: View>(
_ condition: Bool,
transform: (Self) -> Content
) -> some View {
if condition {
transform(self)
} else {
self
}
}
}
The intention is good: apply a modifier only when a condition holds. It compiles, it is convenient, and it looks harmless. But it isn’t entirely harmless.
Important: The problem is not that
applyIffails to compile, but that everyifcreates two branches with their own identity. When the condition flips, SwiftUI destroys the view’s state.
What ViewBuilder actually builds
@ViewBuilder is not just syntactic sugar for choosing one view or another. It is a result builder: it transforms the function body into a type structure.
When we use the helper like this:
MyView()
.applyIf(isEnabled) {
$0.background(Color.red)
}
the compiler produces something equivalent to:
_ConditionalContent<Content, Self>
_ConditionalContent is an internal SwiftUI type that represents two possible branches. In the example, one branch contains the modified view and the other contains the original view:
_ConditionalContent<
ModifiedContent<MyView, _BackgroundStyleModifier<Color>>,
MyView
>
Note: What matters is understanding that the
ifis not evaluated as a condition inside a single modifier: the resulting view has two possible structural identities.
Structural identity, not just values
SwiftUI distinguishes between a view’s value and its identity in the hierarchy. Structural identity depends on the view’s type and position in the tree. An if/else inside a ViewBuilder creates two different positions: the true branch and the false branch.
When condition changes, SwiftUI is not changing the parameter of a single modifier. It is removing one branch and inserting the other. If there is an animation, the result is a transition —a fade, for example— instead of an interpolation between the two values.
This also affects state. SwiftUI associates @State, @StateObject, @FocusState, and @GestureState with the view’s lifetime and identity. If the view changes branches, its storage disappears and is initialized again.
With the helper defined above, the example can be tested directly in a #Preview:
struct Stateful: View {
@State private var text = ""
var body: some View {
TextField("Name", text: $text)
.textFieldStyle(.roundedBorder)
.padding()
}
}
struct Sample: View {
let isEnabled: Bool
var body: some View {
Stateful()
.applyIf(isEnabled) {
$0.background(Color.red)
}
}
}
struct SamplePreview: View {
@State private var isEnabled = false
var body: some View {
VStack(spacing: 24) {
Sample(isEnabled: isEnabled)
Button {
isEnabled.toggle()
} label: {
Text(isEnabled ? "Disable applyIf" : "Enable applyIf")
.fontWeight(.semibold)
.frame(maxWidth: .infinity)
.padding()
.background(Color.blue)
.foregroundStyle(.white)
.clipShape(RoundedRectangle(cornerRadius: 12))
}
Text("isEnabled: \(isEnabled.description)")
.font(.caption)
.foregroundStyle(.secondary)
}
.padding()
}
}
#Preview {
SamplePreview()
}
Toggling isEnabled makes the TextField lose the text the user had typed. The same happens with a @StateObject created inside the conditional view. It’s not that SwiftUI clears state for no reason: from its perspective, the view has moved to a different position in the tree.
There is an important nuance: if the state lives in a parent whose identity doesn’t change, it survives. The problem affects state owned by the view that changes branches.
How to preserve identity
The practical rule is: if both branches represent the same view with a different configuration, try to keep a single type and change only the value.
When the modifier accepts a conditional value, that is the most direct option:
MyView()
.background(isEnabled ? Color.red : Color.clear)
MyView()
.frame(width: isEnabled ? 200 : 100)
MyView()
.opacity(isEnabled ? 1 : 0)
You can also wrap the condition in a stable ViewModifier:
struct ConditionalBackground: ViewModifier {
let isEnabled: Bool
func body(content: Content) -> some View {
content.background(isEnabled ? Color.red : Color.clear)
}
}
extension View {
func conditionalBackground(_ isEnabled: Bool) -> some View {
modifier(ConditionalBackground(isEnabled: isEnabled))
}
}
Note: The type
ModifiedContent<MyView, ConditionalBackground>doesn’t change; theBoolis just a parameter. Identity is preserved and the modifier remains applied at all times.
When an if is the right tool
This is not about banning applyIf or if statements in ViewBuilder. Branches are the right tool when we genuinely want two different structures: showing a loading screen or the content, an empty state or a list, one view or another.
The key is to choose deliberately:
- If you want to change the structure, use
if/elseand accept that identity changes. - If you want to change only a property of the same view, preserve identity and pass the value to the modifier.
- If state must survive a structural change, lift it to a stable parent or to a model that isn’t destroyed.
Conclusion
applyIf is convenient, but it hides an architectural decision: every if in a ViewBuilder creates two branches with their own identity. That resets the state of the view that changes branches.
Before adding a conditional helper, it’s worth asking whether the two branches are really two different views or the same view with a different configuration. If it’s the latter, keeping the type stable is the more predictable option.
References
Publicado el Published on