apple / apple/swift-openapi-generator
Add an option to disable default = nil initializers for optional properties
- Dominant language
- Swift
- Stars
- 2k
- Forks
- 182
- Avg merge
- 13h 28m
- Merged PRs (30d)
- 5
Description
### 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! 🙏
Contributor guide
Research direction
Start by tracing where Swift model initializers are synthesized and where generator configuration is loaded. Confirm how the proposed option should affect optional-property defaults, then verify generated models use either `= nil` or required optional parameters according to the selected setting.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- openapi, swift
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100