swift-memberwise-init-macro
swift-memberwise-init-macro copied to clipboard
Always default `optionalsDefaultNil` to `false`, despite Swift 5
Description
Swift provides non-public initializers that default optionals to nil
. A design tenet of MemberwiseInit has been to strive to be a pure superset of Swift's memberwise initializer, and this approach has largely served it well.
However, I'm convinced that MemberwiseInit should deviate from Swift 5 and always default _optionalsDefaultNil
to false, regardless of access level.
Swift's behavior is:
- complex and often not familiar to developers,
- lamented by (at least one of) its designers,
- different for
Int?
andOptional<Int>
(defaultednil
and not defaulted, respectively), - hasn't been changeable due to Swift's source compatibility principles, but could be “corrected” in Swift 6. [Update: Swift 6 didn't change this behavior.]
MemberwiseInit can offer a more straightforward approach: Optionals should not default to nil
unless explicitly specified by the developer.
This has been debated at length on the forums:
- https://forums.swift.org/t/unexpected-memberwise-inits-for-all-optional-structs/41169
- https://forums.swift.org/t/pre-pitch-remove-the-implicit-initialization-of-optional-variables/52300
- https://forums.swift.org/t/pitch-remove-default-initialization-of-optional-bindings/6961