1

I seem to be misunderstanding something about access control modifiers in Swift. Here is my code from a playground:

class Something {
    private (set) var name :String {
    get { return "" }
    set {}
    }
}
var thing = Something();
thing.name = "";

My intuition and experience from other languages tells me that there should be a compiler error on the last line.

The book I'm learning from however states that private means the member being modified is only accessible from the same source file.

Am I safe to assume this scenario would generally be an error in most projects, and this is only because I'm running this code in a playground?

Is the statement that private members can only be accessed from the same source file totally accurate?

4

2 回答 2

2

此规则适用于所有版本的 Swift 2。它也适用于您的示例,并且有效,因为您的 setter 代码位于调用 setter 的同一文件中(如果我正确理解您的示例)。

允许顶级赋值表达式thing.name = "";是因为它在操场上运行。在操场之外,这种特殊的顶级分配在大多数情况下都是非法的(也例外!)。


什么是“顶级代码”以及它适用于何处的额外解释;来自官方 Swift博客

但是,大多数 Swift 源文件中不允许使用顶级代码。为清楚起见,任何未写在函数体、类中或以其他方式封装的可执行语句都被认为是顶级的。我们有这个规则是因为如果您的所有文件中都允许使用顶级代码,则很难确定从哪里启动程序。

...

您会注意到,之前我们说过,大多数应用程序的源文件中不允许使用顶级代码。例外是一个名为“main.swift”的特殊文件,它的行为很像游乐场文件,但它是使用您的应用程序的源代码构建的。“main.swift”文件可以包含顶级代码,并且顺序相关的规则也适用。实际上,在“main.swift”中运行的第一行代码被隐式定义为程序的主入口点。这允许最小的 Swift 程序是一行——只要该行在“main.swift”中。

于 2016-08-24T19:21:28.157 回答
1

然而,我正在学习的这本书指出,私有意味着被修改的成员只能从同一个源文件中访问。

您的示例是从同一个源文件访问它。有什么问题?

在 Swift 3 中,privatebecome fileprivate,其中允许从同一个文件的任何地方访问。private在 Swift 3 中具有您期望的行为,其中仅允许在类/结构/枚举本身内进行访问。

于 2016-08-24T19:20:41.533 回答