private , fileprivate,internal,public,open
从整体看,权限 private < fileprivate < internal < public < open
swift官方定义
Swift Access Control
Swift provides five different access levels for entities within your code. These access levels are relative to the source file in which an entity is defined, and also relative to the module that source file belongs to.
Open access and public access enable entities to be used within any source file from their defining module, and also in a source file from another module that imports the defining module. You typically use open or public access when specifying the public interface to a framework. The difference between open and public access is described below.
Internal access enables entities to be used within any source file from their defining module, but not in any source file outside of that module. You typically use internal access when defining an app’s or a framework’s internal structure.
File-private access restricts the use of an entity to its own defining source file. Use file-private access to hide the implementation details of a specific piece of functionality when those details are used within an entire file.
Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. Use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.
Private
private是这些修饰词中,访问权限最严格的。private用来修饰类和方法或者属性时,该类、属性、方法无法在该类以外使用,比如修饰类时,其他类无法使用该类
修饰方法时,其他类无法使用该方法 修饰属性时,其他类无法使用该属性,读取也不行
这里其实稍微有个悖论,如果用private来修饰类时,其他类都无法使用该类,那这个类的设计目的是什么呢?只能自调用?
fileprivate
fileprivate这个修饰词挺有意思,它意味着修饰的东西只能在该文件中访问,而不能在其他文件中访问(我学过的语言中,只有swift是这么设计的,但具体为什么设计基于文件的访问权限,我没有查到资料 )
比如在A.swift中,其他类可以访问该类,而在B.swift中是无法访问filePrivateClass的
internal
internal是默认的修饰词,在该模块内部可以被访问。 如果是封装库,则整个库都可以访问该类,而库外的代码是无法访问的。 如果是App中的类,则整个App都可以访问该类
Public 和 Open
这两个修饰词之所以放在一起,是因为他们的属性很相似,都是在模块的外部可以访问。 但是Public的修饰内容在外部无法被继承或者重写,而Open可以
使用原则
Access levels in Swift follow an overall guiding principle: No entity can be defined in terms of another entity that has a lower (more restrictive) access level. 不能用一个更低访问级别的实体来定义当前实体
这句话看着不太好懂,我觉得可以这么理解,不要破坏一个类的权限,比如类filePrivateClass是fileprivate,如果你用public修饰,则破坏了它的权限,因为其根本属性时fileprivate,用public修饰就让编译器不知道如何来编译了
Getter和setter
我们使用Objective-C的时候,通常会用readOnly等修饰词来控制读写权限,而在swift中,我们可以通过private修饰set和get做到
可读写
默认的权限internal即可
class Person : NSObject {
var name : String? = nil
}
不可读
class Person : NSObject {
private var name : String? = nil
}
不可以写
class Person : NSObject {
private(set) var name : String? = nil
}
|