我对范围还是有点困惑,我认为变量只能在其范围内访问,这就是我所理解的一般方式
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
函数访问,因为changeColor
与 color
具有相同的作用域。但是 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/