Skip to content

Latest commit

 

History

History
73 lines (57 loc) · 3.5 KB

File metadata and controls

73 lines (57 loc) · 3.5 KB

Initializers in Swift

Table Of Contents

  1. Memberwise Initializers in Structs
    1. Memberwise Initializer
    2. When We Get a Memberwise Initializer?
  2. Designated Initializers in Classes
  3. Convenience Initializers in Classes
  4. Failable Initializers
  5. Required Initializers in Classes
  6. References

Memberwise Initializers in Structs

Memberwise Initializer

  • 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.

When We Get a Memberwise Initializer?

We get a memberwise initializer when:

  • All of its members are either:
    • Visible (public or internal),
    • Or computed,
    • Or wrapped by a wrapper that provides a default value (SwiftUI’s State).
  • There is no custom initializer.
    • Workaround to have a custom initializer and memberwise initializer: add a custom initializer in the extension.

Designated Initializers in Classes

  • 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 init keyword before the designated initializer.
  • What a designated initializer can/cannot do?
    • Can call an initializer of the superclass.
    • Cannot call a convenience initializer of the superclass.

Convenience Initializers in Classes

  • 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 convenience keyword before the convenience initializer.
  • 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.

Failable Initializers

  • 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.

Required Initializers in Classes

  • 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 required keyword before the required initializer.

References