Cómo poblar tus #Previews en SwiftUI

Guía de SwiftUI Preview con PreviewModifier para caché y datos asíncronos en Xcode, con el ejemplo BookProvider. Soluciones de Q2BSTUDIO para apps a medida e IA.

7 sept 2025 • 2 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Apple creó la macro #Preview para previsualizar de forma rápida tus vistas de SwiftUI en Xcode.

Ejemplo mínimo: #Preview { BookView() }

Incluso puedes preparar datos dentro del propio #Preview, por ejemplo: let books = [Eros y Agape de Anders Nygren, Comentario a Gálatas de Martin Luther]; luego invocas BookView(books: books).

El reto aparece cuando necesitas cachear los datos de inicialización del preview o, en otro caso frecuente, cuando esos datos deben obtenerse con código asíncrono.

Una aproximación inicial que se vio por ahí fue algo como: #Preview { @Previewable @State var books: [Book] = []; if books.isEmpty { ProgressView().task { books = await myAsyncFunc() } } else { BookView(books: books) } }. Aunque funciona, es una solución poco elegante y además no ofrece caché.

La vía más alineada con las prácticas de Apple es aprovechar PreviewModifier para generar y compartir contexto entre actualizaciones del preview, habilitando caché y soporte async:

struct BookProvider: PreviewModifier { static func makeSharedContext() async -> [Book] { return await myAsyncBookGenerator() } func body(content: Content, context: [Book]) -> some View { BookView(books: context) } }

La idea es simple: makeSharedContext puede producir cualquier tipo que necesites para tu preview. Si no lo defines, por defecto es Void. En body recibes el content que provee #Preview y el context producido por makeSharedContext, y puedes devolver la vista final que quieras.

Para aplicar el modificador: #Preview(traits: .modifier(BookProvider())) { BookView() }.

Un apunte adicional: sería interesante un enfoque con genéricos para que Content no fuese una vista con type erasure, pero por cómo funcionan los protocolos aquí, no es trivial.

En Q2BSTUDIO te ayudamos a crear aplicaciones a medida y software a medida con SwiftUI y el resto del ecosistema Apple, optimizando tus #Previews con datos simulados, caché y carga asíncrona, y conectándolos con backends y servicios CI. Si buscas acelerar tu roadmap digital con equipos expertos y metodologías ágiles, descubre nuestro enfoque de aplicaciones a medida y software a medida.

También impulsamos la adopción de inteligencia artificial en tus flujos de desarrollo y negocio, desde generación de datos de prueba con modelos, agentes IA para automatización y soporte en tiempo real, hasta integración con servicios cloud aws y azure, ciberseguridad y pentesting, y analítica avanzada con power bi. Conoce nuestras soluciones de inteligencia artificial e ia para empresas para llevar tus productos a otro nivel.

Palabras clave relacionadas: aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA, power bi.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat