- Memberwise Initializers in Structs
- Designated Initializers in Classes
- Convenience Initializers in Classes
- Failable Initializers
- Required Initializers in Classes
- References
- An initializer generated automatically by a compiler for a struct.
- Access level is
internal.- We can use memberwise initializers internally within the module in which their type is defined.
We get a memberwise initializer when:
- All of its members are either:
- Visible (
publicorinternal), - Or computed,
- Or wrapped by a wrapper that provides a default value (SwiftUI’s
State).
- Visible (
- There is no custom initializer.
- Workaround to have a custom initializer and memberwise initializer: add a custom initializer in the extension.
- What is a designated initializer?
- Fully initializes all properties introduced by that class.
- Calls an appropriate superclass initializer.
- How to use a designated initializer?
- Use the
initkeyword before the designated initializer.
- Use the
- What a designated initializer can/cannot do?
- Can call an initializer of the superclass.
- Cannot call a convenience initializer of the superclass.
- What is a convenience initializer?
- A special, secondary initializer.
- Make it easier to create instances of a type by providing alternative ways to set its initial state.
- How to use a convenience initializer?
- Use the
conveniencekeyword before the convenience initializer.
- Use the
- What a convenience initializer can/cannot do?
- Can call other initializers (designated or convenience) from the same class.
- Cannot call the initializers of the superclass.
- What is a failable initializer?
- A special initializer that can return nil if the initialization process fails, allowing for the creation of optional instances.
- How to use a failable initializer?
- Use the
init?keyword before the failable initializer.
- Use the
- What is a required initializer?
- A special initializer.
- Must be implemented by any subclass, ensuring that certain properties are properly initialized in the inheritance chain.
- We don't have to provide an explicit implementation of a required initializer if we can satisfy the requirement with an inherited initializer.
- How to use a required initializer?
- Use the
requiredkeyword before the required initializer.
- Use the