Skip to main content
A memberwise initializer is a compiler-synthesized initialization method automatically provided for struct types in Swift. It allows instances to be initialized by passing values for the struct’s stored properties, matching their exact names and types, without requiring explicit initializer declarations.

Core Mechanics

When a struct is defined without any custom initializers, the Swift compiler inspects its stored properties and generates an init method. The parameters of this method directly correspond to the properties in the order they are declared.

Rules for Synthesis

The generation of the memberwise initializer is governed by strict compiler rules regarding type, existing initializers, and property characteristics. 1. Type Restriction Memberwise initializers are exclusive to value types, specifically struct declarations. They are not synthesized for class or enum types. 2. Custom Initializer Suppression If a custom init block is defined directly within the primary body of the struct, the compiler suppresses the synthesis of the memberwise initializer.
3. The Extension Bypass To define custom initializers while retaining the compiler-generated memberwise initializer, the custom initializers must be declared inside an extension of the struct.

Property Mutability and Default Values

The signature of the synthesized initializer dynamically adjusts based on the mutability (let vs. var) and the presence of default values for the stored properties.
  • Uninitialized var or let: Becomes a required parameter in the initializer.
  • var with a default value: Becomes a parameter with a default argument, allowing it to be omitted during initialization.
  • let with a default value: Is completely excluded from the memberwise initializer signature, as constant properties with default values cannot be reassigned.

Access Control Limitations

The access level of the synthesized memberwise initializer defaults to internal. However, it is subject to the following access control constraints:
  • Restrictive Inheritance: If any stored property has a more restrictive access level (e.g., private or fileprivate), the entire memberwise initializer inherits that restrictive access level.
  • Public Structs: If a struct is marked public, the synthesized memberwise initializer remains internal. To expose a memberwise initializer across module boundaries, a public init must be explicitly written by the developer.
Tired of Poor Swift Skills? Fix That With Deep Grasping!Learn More