Search code examples
iosswiftaccess-controlinitializer

Why do memberwise initializers become 'private' when the structure contains a private property?


The default memberwise initializer for a structure type is considered private if any of the structure’s stored properties are private.

(Source: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/accesscontrol/)

What is the reason as to why the memberwise initializer becomes 'private' when a stored property is 'private'?

And is there a reason why the same does not apply for custom initializers?


Solution

  • "Because otherwise the compiler would overrule our intention to keep the property private if it synthesized a public member wise init. As for a custom init, well then it is our choice to allow the property to be initialized from outside of our custom type." (@joakimdanielson)

    Also from Swift Forums:

    enter image description here

    Another (possible) explanation from Hacking With Swift Forums:

    enter image description here