swift - 仍然可以从外部访问私有(private)值

标签 swift class scope

我对范围还是有点困惑,我认为变量只能在其范围内访问,这就是我所理解的一般方式

class Car {
    let manufacturer: String

    private(set) var color: String

    init() {
        manufacturer = "Ford"
        color = "Black"
    }

    func changeColor(color: String){
        self.color = color
    }
}

var carOfTim = Car()

carOfTim.changeColor("Red") // only "changeColor" fun can update the color
print(carOfTim.color)


//why I can do this?
carOfTim.color = "Green"
print(carOfTim.color) // it prints the "Green"!

问题:我认为私有(private)变量color只能被changeColor函数访问,因为changeColorcolor 具有相同的作用域。但是 carOfTim.color = "Green" 仍然可以更新颜色变量,为什么?

猜想:由于我使用了 Xcode Playground ,所以所有内容都输入到同一个普通“终端”,因此如果我将 Car 类放入不同的文件夹,它们可能具有相同的作用域, carOfTim.color = "Green" 可能不再有效。

如有错误请指正。非常感谢您的时间和帮助。

最佳答案

在 Swift 中,private 的范围是源文件,而不是声明实体。这是一个设计决定。

来自 the documentation :

Private access restricts the use of an entity to its own defining source file. Use private access to hide the implementation details of a specific piece of functionality.

...

NOTE

Private access in Swift differs from private access in most other languages, as it’s scoped to the enclosing source file rather than to the enclosing declaration. This means that a type can access any private entities that are defined in the same source file as itself, but an extension cannot access that type’s private members if it’s defined in a separate source file.

在下面的示例中(粗体是我的):

However, the access level for the numberOfEdits property is marked with a private(set) modifier to indicate that the property should be settable only from within the same source file as the TrackedString structure’s definition.

关于swift - 仍然可以从外部访问私有(private)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37532451/

相关文章:

c++ - 在 C++ 文件中声明全局类实例

Python重写类(非实例)特殊方法

python - 嵌套类实例的有用默认 __repr__

javascript - 从调用范围访问 javascript 变量

javascript - 当变量在单独的循环中定义时,在循环内调用该变量

ios - 选择 UITableView 中的所有行,并在数组中附加标签

ios - iPhone 用户加速度不为零

ios - 如何在不重新启动应用程序 swift4 的情况下更改本地化语言?

swift - 符合 CBCentralManagerDelegate 协议(protocol)

JavaScript:函数及其作用域/词法环境如何传递?