私人变量可以从班级外部访问 [英] Private var is accessible from outside the class
问题描述
这是在Playground中完成的,只是为了简化.
This was done in Playground, just to simplify.
class MyPrivateVar
{
private var priv: String?
}
var myInstance = MyPrivateVar()
myInstance.priv = "Something"
没有编译器警告.实际上,自动完成显示priv
没有问题.
我的理解是,在类{}的范围之外,我不应该看到私有的任何内容,func
或var
.
No compiler warning. In fact auto-complete is showing priv
without a problem.
My understanding is that outside the boundaries of {} of the class, I'm not supposed to be able to see a private anything, func
nor var
.
我想念什么吗?
推荐答案
Swift中的访问修饰符与其他语言的实现方式不同.共有三个级别:
Access modifiers in Swift are implemented differently than other languages. There are three levels:
private
:仅在该特定文件内
internal
:仅在模块(项目)中可访问
internal
: accessible only within the module (project)
public
:可从任何地方访问
除非另有标记,否则默认情况下,您编写的所有内容均为internal
.
Unless marked otherwise, everything you write is internal
by default.
Swift博客发布了有关访问控制的帖子.在Beta 4中进行了介绍,并且
The Swift blog had a post about access control when the features were introduced in beta 4, and Apple's documentation has a chapter as well.
这篇关于私人变量可以从班级外部访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!