对计算属性的 Swift 访问控制 : why does this work?

标签 swift class-visibility

<分区>

我似乎对 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”.

关于对计算属性的 Swift 访问控制 : why does this work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39131381/

相关文章:

json - 在 Swift 中将 JSON 转换为 NSData,以及将 NSData 转换为 JSON

ios - 如何按值传递引用类型?

java - 包保护类中的公共(public)方法是否有任何理由?

c# - 允许 Newtonsoft 的 JsonConvert 访问内部 getter/setter

Kotlin:可见性修饰符更改匿名对象的类型

swift - 在 swift 中表达具有动态范围的 for 循环

ios - 更改 UItableView 高度后,我的滚动不再起作用。无法到达底部数据

swift - 快速替换 NSMutableArray 中的值的问题

Java 接口(interface)的可见性降低,只是没有