Swift init(), De Una Vez Por Todas

Guía completa sobre inicializadores en Swift: memberwise, designados, de conveniencia, failable init, required, enum y más. Aprende a usarlos correctamente y evita errores.

22 mar 2025 • 2 min read • Q2BSTUDIO Team

Empresa-Software-Apps-InteligenciaArtificial

Hola! Mi nombre es Kiryl Famin, y soy un desarrollador iOS.

Hoy quiero analizar en profundidad un tema aparentemente simple: los inicializadores en Swift. A pesar de su simplicidad aparente, la falta de una comprensión completa del tema puede llevar a errores frustrantes que muchas veces se buscan solucionar rápidamente, sin entender realmente la causa.

En este artículo, cubriremos todo lo relacionado con inicializadores, incluyendo:

  • Cómo mantener el inicializador miembro de una estructura mientras se define uno personalizado
  • Por qué no siempre es necesario definir un inicializador en clases
  • Por qué llamar a super.init no siempre es obligatorio en un inicializador designado
  • Por qué todos los campos de una subclase deben estar poblados antes de llamar a super.init
  • Cómo acceder a todos los inicializadores de la clase padre con la menor cantidad de sobrescrituras posibles
  • Cuándo es realmente necesario un inicializador required
  • Por qué UIView.init() siempre se llama sin parámetros, pero init(frame:) y init(coder:) sí se sobrescriben

En Q2BSTUDIO, somos una empresa de desarrollo y servicios tecnológicos especializada en crear soluciones a medida para diversas plataformas. Nos apasiona compartir conocimientos con la comunidad y mejorar continuamente la experiencia de desarrollo con tecnologías modernas como Swift.

Ahora, avancemos paso a paso para comprender a fondo este tema.

Resumen en Español:

  • Todos los campos deben estar poblados en un inicializador.
  • Las propiedades var opcionales tienen un valor por defecto de nil.
  • Las estructuras reciben un inicializador miembro automáticamente.
  • El inicializador miembro desaparece cuando se define uno personalizado.
  • Un inicializador designado se asegura de que todos los campos sean inicializados y llama a super.init().
  • Un inicializador de conveniencia simplifica el proceso llamando a otro inicializador designado.
  • Los inicializadores de conveniencia siempre llaman a self.init, mientras que los designados llaman a super.init.
  • Si una subclase define nuevas propiedades, pierde los inicializadores de conveniencia de su superclase.
  • Para restaurar los inicializadores de conveniencia de una superclase, es necesario sobrescribir todos los inicializadores designados.
  • Para minimizar la cantidad de sobrescrituras, se pueden usar inicializadores de conveniencia sobrescritos.
  • Si una subclase no introduce nuevos parámetros, hereda todos los inicializadores de su superclase.
  • Si una superclase solo tiene init() sin parámetros, este se llama automáticamente en las subclases.
  • Un inicializador required asegura que las subclases lo implementen, útil en genéricos, protocolos y llamadas a Self().
  • UIView.init() llama internamente a init(frame:) o init(coder:).
  • Un inicializador fallable devuelve un valor opcional.
  • Las enumeraciones con valores crudos obtienen un inicializador init?(rawValue:) automáticamente.
  • Todos los inicializadores en una enumeración deben asignar un valor a self.

Esperamos que este artículo te haya resultado útil. En Q2BSTUDIO creemos en la excelencia del desarrollo y en compartir conocimientos para ayudar a otros desarrolladores a mejorar sus habilidades cada día.

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