Skip to content

Add an option to disable default = nil initializers for optional propertiesΒ #847

@acolombero-etx

Description

@acolombero-etx

Motivation

Summary

When generating Swift models, optional properties (String?, for example) are automatically assigned a default value of = nil in the synthesized initializer:

package init(
    email: String? = nil,
    firstName: String? = nil
)

This behavior is currently not configurable.
For some use cases, it is desirable to generate:

package init(
    email: String?,
    firstName: String?
)

i.e. optional fields without a default value.

Why this matters

Prevents accidental omission of new fields

When new optional fields are added in the OpenAPI spec, the current behavior allows them to be silently ignored (because default nil is automatically applied).
Without default values, Swift will enforce explicitly passing all fields, avoiding accidental data loss.

More explicit API usage

The caller must decide whether a field is intentionally nil, instead of relying on silent defaults.

More idiomatic in strongly typed update payloads

Particularly in partial update payloads (PATCH or update DTOs), explicitness is extremely valuable.

Proposed solution

Add a configuration option in openapi-generator-config.yaml:

models:
  initializer-defaults:
    optional-properties: omit # or: require

Or at the very least:

omitDefaultNilForOptionalProperties: true

Alternatives considered

Using a post-processing script to remove = nil, e.g. using sed:

sed -i '' -E 's/([a-zA-Z0-9_]+: [A-Za-z0-9\._]+)\? = nil/\1?/g' *.swift

But this is not ideal, and it breaks if the code generator changes its formatting.

Additional information

This would help avoid mistakes, make APIs safer, and give developers more control over initialization semantics.

Thank you for considering it! πŸ™

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind/featureNew feature.status/triageCollecting information required to triage the issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions