我似乎对 Swift 中的访问控制修饰符有一些误解。这是我在 Playground 上的代码:
class Something {
private (set) var name :String {
get { return "" }
set {}
}
}
var thing = Something();
thing.name = "";
我的直觉和其他语言的经验告诉我,最后一行应该有编译错误。
然而,我正在学习的书指出,private 意味着被修改的成员只能从同一源文件访问。
我是否可以安全地假设这种情况在大多数项目中通常都是错误的,而这只是因为我在 Playground 上运行这段代码?
只能从同一源文件访问私有(private)成员的说法是否完全准确?
此规则对所有版本的 Swift 2 都有效。它对您的示例也有效,并且之所以有效,是因为您的 setter 代码位于调用 setter 的同一文件中(如果我理解正确的话)。
顶级赋值表达式 thing.name = "";
是允许的,因为它在 Playground 上运行。在 Playground 之外,这种特殊的顶级分配在大多数情况下都是非法的(有异常(exception)!)。
额外解释什么是“顶级代码”及其适用范围;来自 Swift 官方博客 here :
However, top-level code is not allowed in most of your Swift source
files. For clarity, any executable statement not written within a
function body, within a class, or otherwise encapsulated is considered
top-level. We have this rule because if top-level code were allowed in
all your files, it would be hard to determine where to start the
program.
...
You’ll notice that earlier we said top-level code isn’t allowed in
most of your app’s source files. The exception is a special file named
“main.swift”, which behaves much like a playground file, but is built
with your app’s source code. The “main.swift” file can contain
top-level code, and the order-dependent rules apply as well. In
effect, the first line of code to run in “main.swift” is implicitly
defined as the main entrypoint for the program. This allows the
minimal Swift program to be a single line — as long as that line is in
“main.swift”.