In a Swift struct, when does the compiler synthesize a memberwise initializer, and why does adding your own init make it disappear?
answer
- structs only, never classes
- one labelled parameter per stored property
- initial values become default arguments
- the body versus an extension
- internal at most; private properties restrict it
basics
~20 sSwift synthesizes a memberwise initializer for a struct that declares no initializer in its own body, with one labelled parameter per stored property in declaration order. An init written in the body suppresses it; one written in an extension keeps both.
solid answer
~40 sEvery struct that declares no initializer in its body gets an implicit memberwise initializer: one parameter per stored property, labelled with the property name, in declaration order. A `var` with an initial value becomes a default argument (Swift 5.1), an Optional `var` defaults to `nil`, and a `let` with an initial value is left out because it can never be reassigned. Declaring `init(payload:)` inside the struct removes the synthesized one, so the compiler can't let callers skip setup the custom init performs; declaring it in an `extension` keeps both. The memberwise initializer is `internal` at most, so a `public` struct needs a hand-written `public init`. A `private` stored property without an initial value makes it `private`; since Swift 6.4 (SE-0502) a less-accessible property that has an initial value is simply left out instead.
code
swift · 19 linesstruct User {
let id: String
var name: String
var isPremium = false
let source = "server"
}
extension User {
// Declared in an extension, so the memberwise initializer survives.
init(payload: [String: String]) {
self.init(id: payload["id"] ?? "",
name: payload["name"] ?? "Guest",
isPremium: payload["tier"] == "premium")
}
}
let a = User(id: "u1", name: "Ana") // isPremium defaults to false
let b = User(payload: ["id": "u2", "tier": "premium"])
print(a.isPremium, b.name, b.isPremium, b.source)go deeper
Recall that only structs get a memberwise initializer, that its labels are the property names in declaration order, and that defaulted var properties can be left out of the call.
Explain why an init in the body suppresses it, how the extension placement keeps it, and the access-level rules, including the internal ceiling that forces a public init in frameworks.
Show you can predict a broken call site: a new private property without a default, an init moved into the body, or a framework type used across modules, and name the Swift 6.4 SE-0502 change.
Frame the memberwise initializer as part of a model type's API: decide where custom initializers live and when a module boundary needs an explicit public init.
## What the compiler synthesizes A **memberwise initializer** is an initializer the compiler writes for a **struct** so that callers can set every stored property by name. For a `User` model built from a server payload: - it has **one parameter per stored property**, labelled with the property's name, in **declaration order** (`User(id:name:isPremium:)`; passing the labels out of order is an error such as `argument 'b' must precede argument 'a'`); - a `var` with an **initial value** becomes a parameter with a **default argument** (since Swift 5.1, SE-0242), so `var isPremium = false` can be omitted at the call site; - an **Optional `var`** without an explicit value is default-initialized to `nil`, so it can be omitted too; an Optional **`let`** has no such default and must be passed; - a **`let` with an initial value** is not a parameter at all, because that constant can never be assigned again. **Classes never get one.** A class receives only a **default initializer** `init()` when every stored property has a default value and the class declares no initializer; a struct in that situation receives both `init()` and the memberwise initializer. ## Why your own init removes it The rule is about **where** the custom initializer is declared: 1. Declare any `init` **inside the struct's body**, and the compiler stops synthesizing both the memberwise initializer and the default `init()`. 2. Declare it in an **extension** of the struct, and the synthesized initializers survive next to yours. The Swift book gives the reason: a custom initializer in the type usually does essential setup (normalizing a payload, validating an ID), and an automatic initializer left in place would let callers bypass it. If that is not your intent, the extension placement says so explicitly. Call sites show the difference at once. With `init(payload:)` in the body, `User(id: "u1", name: "Ana")` fails with `extra arguments at positions #1, #2 in call` and `missing argument for parameter 'payload' in call`, because the only remaining initializer is the custom one. ## Its access level The memberwise initializer is never more visible than **`internal`**, whatever the struct's own access level. | Struct's stored properties | Memberwise initializer | |---|---| | all `internal` or `public` | `internal` | | a `private` property **without** an initial value | `private` | | a `fileprivate` property **without** an initial value | `fileprivate` | | a less-accessible property **with** an initial value (Swift 6.4) | stays `internal`; that property is not a parameter | Two consequences come up in reviews: - A **`public` struct in a framework** cannot be built with memberwise syntax from another module; the framework must write a `public init` itself. - A `private var token: String` with no initial value makes the initializer `private`, and another file then sees `'User' initializer is inaccessible due to 'private' protection level`. ## The Swift 6.4 change (SE-0502) Before Swift 6.4, adding something as harmless as `private var retryCount = 0` to an internal struct made the whole memberwise initializer `private`, which broke every call site in other files. **SE-0502**, implemented in Swift 6.4, changes the rule: - a stored property that **has an initial value** and is **less accessible** than the most accessible memberwise-initializable property (capped at `internal`) is **left out** of the memberwise initializer, which keeps its wider access; - a less-accessible property **without** an initial value is still a parameter and still restricts the initializer, exactly as before; - for source compatibility the compiler also synthesizes a **compatibility overload** with the old parameter list, usable only where the old, restricted initializer was usable (in practice the same file), until a future language mode. The feature is listed in `Features.def` as a baseline language feature, so it is on in both Swift 5 and Swift 6 language modes with a 6.4 compiler. The Swift book's access-control chapter at the 6.4 tag still describes the older rule; the compiler is the authority here. ## A practical pattern for models For a `User` decoded from a server payload, the common shape is: - stored properties with sensible defaults (`var isPremium = false`) so tests and previews can build values with a short memberwise call; - a domain-specific initializer such as `init(payload:)` in an **extension**, delegating to the memberwise initializer with `self.init(...)`; - a hand-written `public init` only when the type crosses a module boundary. That keeps one source of truth for how a `User` is assembled while the compiler keeps writing the boilerplate.
- Why can't another module build your public struct with memberwise syntax?The synthesized memberwise initializer is `internal` at most, even when the struct is `public`. Code in another module therefore sees no accessible initializer. The framework has to declare an explicit `public init(...)` that assigns each property; the compiler will not widen the synthesized one.
- In Swift 6.4, does a private stored property still make the memberwise initializer private?Only when it has no initial value. `private var token: String` is still a parameter, so the initializer becomes `private` and other files get `'User' initializer is inaccessible due to 'private' protection level`. `private var retryCount = 0` is left out since SE-0502, so the initializer stays `internal`.
- How does an Optional property behave in the memberwise initializer?An Optional `var` without an explicit value is default-initialized to `nil`, so its parameter gets a `nil` default and can be omitted. An Optional `let` gets no such default and must be passed, because a constant is initialized exactly once and the memberwise call is where that happens.
- Classes get a synthesized memberwise initializer just like structs do.
- Any custom init removes the memberwise initializer, even one declared in an extension.
- A public struct's synthesized memberwise initializer is public too.
- A let property with an initial value can be overridden through the memberwise call.
- In Swift 6.4, adding private var retryCount = 0 makes an internal struct's memberwise initializer private.
Assumes Swift 6.4: SE-0502 leaves a less-accessible stored property that has an initial value out of the memberwise initializer; before 6.4 such a property was a parameter and made the initializer private or fileprivate.