Designated Initializers VS Convenience Initializers !
If you're working with Swift, you already know how powerful and versatile this programming language can be. Swift has a feature that makes it even more dynamic? We're talking about Initializers - special methods that preparing an instance of a class, structure, or enumeration for use, preparing involves setting an initial value for each stored property and performing any other setup that is required before the new instance is ready for use. there are two types of initializers in Swift: Designated Initializers and Convenience Initializers.
- Designated Initializers (init) :
init(<#parameters#>) <#statements#> }
- Primary method for initializing a class, ensuring that all the properties are set correctly.
- Classes have one designated initializer, but can easily have more.
- If the subclass has its own designated initializer, it's important to call the designated initializer of the immediate superclass. This ensures that all properties inherited from the superclass are properly initialized. The designated initializer calls continue up the chain of classes until the root class is reached.
- Classes must have at least one designated initializer.
- Chain delegating initializers will end by a call to a non-delegating initializer
- Convenience Initializers (convenience init ) :
convenience init(<#parameters#>) <#statements#> }
- Convenience Initializers are additional, supporting initializers that can be defined in a class in Swift.
- A Convenience Initializer must call a designated initializer from the same class to ensure that all properties are properly initialized.
- While not strictly necessary, Convenience Initializers can be helpful in providing more options and flexibility when creating instances of a class.
- Convenience Initializers can be defined to create an instance of a class for a specific use-case or input value type.
- Convenience Initializers can serve as shortcuts for common initialization patterns, making it easier to create instances of a class in specific situations.
To sum up, Swift's designated and convenience initializers provide flexibility and efficiency when creating code. Designated initializers are the primary way to initialize a class, while convenience initializers offer an additional method. Mastering these two types of initializers is crucial for writing high-quality code.
Sources : The Swift Programming Language Book for Swift 5.8.
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/initialization/#Designated-Initializers-and-Convenience-Initializers
Image Source Ref#: J (originally from Apple Docs
Thanks for reading ...
#SwiftProgramming #iOSDevelopment #MobileDevelopment #SwiftLanguage #Xcode #LearnSwift #CodeNewbie