Saltar al contenido
Skillpedia
Sitios e interfaces (frontend)280 mil · #252

swiftui-patterns

Qué hace

Esta guía enseña buenas prácticas para crear apps modernas para iPhone y Mac con SwiftUI. Explica cómo organizar tu código, gestionar los datos y hacer que la navegación funcione de forma eficiente.

Cuándo usarla

  • ✓Cuando empiezas una app nueva con SwiftUI.
  • ✓Cuando quieres organizar el código de una app que ya existe.
  • ✓Cuando la app va lenta o no responde bien.

Link de la skill

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/swiftui-patterns/SKILL.md

Cópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.

Cómo usar

La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.

Mensaje listo para pegar

Usa esta skill para ayudarme: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/swiftui-patterns/SKILL.md Lee el archivo SKILL.md de ese link y sigue sus instrucciones en mi tarea.
¿Quieres que tu IA encuentre skills como esta por sí sola?Instala el MCP gratis de Skillpedia: una línea, y busca entre 15.000+ skills antes de cada tarea.Instalar en 1 minuto →

Ejemplo de qué pedirle a la IA

“¿Cómo puedo organizar mejor mi código de SwiftUI para la gestión de datos y la navegación?”

5 skills nuevas por semana. 1 minuto de lectura.

Cómo funciona

Muestra cómo usar herramientas concretas de SwiftUI, como `@Observable` para gestionar los datos y `NavigationStack` para la navegación. El objetivo es que el código quede más limpio y la app sea más rápida.

Contenido técnico (SKILL.md original)

Texto original del autor, en inglés, directo de GitHub.

SwiftUI Patterns

Modern SwiftUI patterns for building declarative, performant user interfaces on Apple platforms. Covers the Observation framework, view composition, type-safe navigation, and performance optimization.

When to Activate

  • Building SwiftUI views and managing state (@State, @Observable, @Binding)
  • Designing navigation flows with NavigationStack
  • Structuring view models and data flow
  • Optimizing rendering performance for lists and complex layouts
  • Working with environment values and dependency injection in SwiftUI

State Management

Property Wrapper Selection

Choose the simplest wrapper that fits:

Wrapper Use Case
@State View-local value types (toggles, form fields, sheet presentation)
@Binding Two-way reference to parent's @State
@Observable class + @State Owned model with multiple properties
@Observable class (no wrapper) Read-only reference passed from parent
@Bindable Two-way binding to an @Observable property
@Environment Shared dependencies injected via .environment()

@Observable ViewModel

Use @Observable (not ObservableObject) — it tracks property-level changes so SwiftUI only re-renders views that read the changed property:

@Observable
final class ItemListViewModel {
    private(set) var items: [Item] = []
    private(set) var isLoading = false
    var searchText = ""

    private let repository: any ItemRepository

    init(repository: any ItemRepository = DefaultItemRepository()) {
        self.repository = repository
    }

    func load() async {
        isLoading = true
        defer { isLoading = false }
        items = (try? await repository.fetchAll()) ?? []
    }
}

View Consuming the ViewModel

struct ItemListView: View {
    @State private var viewModel: ItemListViewModel

    init(viewModel: ItemListViewModel = ItemListViewModel()) {
        _viewModel = State(initialValue: viewModel)
    }

    var body: some View {
        List(viewModel.items) { item in
            ItemRow(item: item)
        }
        .searchable(text: $viewModel.searchText)
        .overlay { if viewModel.isLoading { ProgressView() } }
        .task { await viewModel.load() }
    }
}

Environment Injection

Replace @EnvironmentObject with @Environment:

// Inject
ContentView()
    .environment(authManager)

// Consume
struct ProfileView: View {
    @Environment(AuthManager.self) private var auth

    var body: some View {
        Text(auth.currentUser?.name ?? "Guest")
    }
}

View Composition

Extract Subviews to Limit Invalidation

Break views into small, focused structs. When state changes, only the subview reading that state re-renders:

struct OrderView: View {
    @State private var viewModel = OrderViewModel()

    var body: some View {
        VStack {
            OrderHeader(title: viewModel.title)
            OrderItemList(items: viewModel.items)
            OrderTotal(total: viewModel.total)
        }
    }
}

ViewModifier for Reusable Styling

struct CardModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .padding()
            .background(.regularMaterial)
            .clipShape(RoundedRectangle(cornerRadius: 12))
    }
}

extension View {
    func cardStyle() -> some View {
        modifier(CardModifier())
    }
}

Navigation

Type-Safe NavigationStack

Use NavigationStack with NavigationPath for programmatic, type-safe routing:

@Observable
final class Router {
    var path = NavigationPath()

    func navigate(to destination: Destination) {
        path.append(destination)
    }

    func popToRoot() {
        path = NavigationPath()
    }
}

enum Destination: Hashable {
    case detail(Item.ID)
    case settings
    case profile(User.ID)
}

struct RootView: View {
    @State private var router = Router()

    var body: some View {
        NavigationStack(path: $router.path) {
            HomeView()
                .navigationDestination(for: Destination.self) { dest in
                    switch dest {
                    case .detail(let id): ItemDetailView(itemID: id)
                    case .settings: SettingsView()
                    case .profile(let id): ProfileView(userID: id)
                    }
                }
        }
        .environment(router)
    }
}

Performance

…

Preguntas frecuentes

¿Cuál es la diferencia entre `@State` y `@Observable`?

`@State` sirve para datos sencillos que pertenecen a una sola pantalla. `@Observable` sirve para datos más complejos que se pueden compartir y gestionar de forma más eficiente, actualizando solo las partes de la pantalla que realmente necesitan volver a dibujarse.

¿Cómo hago que la navegación entre pantallas sea más sólida?

Usa `NavigationStack` con `NavigationPath`. Así puedes definir claramente a dónde se puede ir y con qué datos, lo que evita errores habituales de navegación.

¿Por qué mi app va lenta?

Puede que se estén volviendo a dibujar partes de la pantalla que no hace falta actualizar. Usa `LazyVStack` para listas grandes y divide tus pantallas en componentes más pequeños, para que solo se actualice lo necesario.

Detalles

Descripción original del autor

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices. Use when building or reviewing SwiftUI views, @Observable state, navigation, or render performance.

repo: affaan-m/ECC

Popularidad

Estrellas en GitHub
280 mil
Posición en el ranking
#252
Licencia
MIT
Actualizada
15/10/2026

¿Te sirve esta skill?

0

Entra para votar.

Comentarios

  • …

Más skills de este repositorio

Skills parecidas