为什么成员初始化器在结构体包含私有属性时会变成 ‘private’?

huangapple go评论66阅读模式
英文:

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?

答案1

得分: 2

"否则,如果编译器生成了一个公共成员智能初始化方法,它就会否定我们保持属性私有的意图。至于自定义初始化方法,那么允许属性从自定义类型外部进行初始化是我们的选择。" (@joakimdanielson)

还有来自Swift论坛的信息:

为什么成员初始化器在结构体包含私有属性时会变成 ‘private’?

来自Hacking With Swift论坛的另一种(可能的)解释

为什么成员初始化器在结构体包含私有属性时会变成 ‘private’?

英文:

"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:

为什么成员初始化器在结构体包含私有属性时会变成 ‘private’?

Another (possible) explanation from Hacking With Swift Forums:

为什么成员初始化器在结构体包含私有属性时会变成 ‘private’?

huangapple
  • 本文由 发表于 2023年7月6日 14:26:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76626040.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定