Init vs Convenience init in Swift

Initializers, also known as constructors in other programming languages, have two types: Designated init and Convenience init. They are used to initialize properties or customize a variable or object for classes or structs.

Designated init

This type of the Initializer is frequently seen in Swift class, also named as primary Initializer

  • Designated initializers are the primary initializers for a class
  • A class must have at least one Designated initializer
  • A struct can have Designated initializers, if not the compiler will automatically generate one with all properties
  • Used to initialize the property values

Example of designated init for a class:

Example of designated init for a struct:

The compiler will automatically add a default initializer with all the properties, which is slightly different from class.

Convenience init

Convenience initializers are secondary initializers for a class supporting a Designated initializer, which must call a Designated initializer for a given class. Mostly used as a convenient way to call initializers. They:

  • Can be override by subclass
  • Must have at least one Designated initializers in the same class or from parent cla

Example of convenience init for a class:

Example of convenience init for a struct:

convenience is not required by struct, the reason is struct can't be inherited by another struct, so the struct init can only call the other init in the same struct.

Optional init

Both Designated init and Convenience init can return optional instance, which is nil.

Example of class

Example of struct

Originally published at https://needone.app on February 15, 2021.

--

--

--

needone.app

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

SwiftUI: How to make Collapsible List?

12 Sites to Hire iOS Developers in 2022 (for Guaranteed Quality)

iOS Accessibility Invert Colors

Mastering Software Engineering in iOS: Open-Closed Principle

How to handle Push Notifications in SwiftUI’s New App Lifecycle?

Build a General Purpose API Kit With Combine

diagram showing the two-way flow of data between a user and a remote database through an API

How to make Pie and Donut chart using SwiftUI?

Environment Variables in Xcode

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Needone App

Needone App

needone.app

More from Medium

3 Tips to a Successful App Development Stream

An attempt to run Server-Side Swift on Raspberry Pi

5 Epiphanies from My First [Digital] WWDC

Building a Renderer with Metal (Part 2)— Setting up a Development Environment