Swift中的'open'关键字是什么? [英] What is the 'open' keyword in Swift?
问题描述
ObjectiveC.swift
标准库中的a>文件包含第228行以下几行代码:
The ObjectiveC.swift
file from the standard library contains the following few lines of code around line 228:
extension NSObject : Equatable, Hashable {
/// ...
open var hashValue: Int {
return hash
}
}
在这种情况下open var
是什么意思,或者open
关键字通常是什么?
What does open var
mean in this context, or what is the open
keyword in general?
推荐答案
open
是Swift 3中的新访问级别,随实现一起引入
的
open
is a new access level in Swift 3, introduced with the implementation
of
自2016年8月7日起,Swift 3快照即可提供该功能, 以及Xcode 8 beta 6.
It is available with the Swift 3 snapshot from August 7, 2016, and with Xcode 8 beta 6.
简而言之:
-
open
类可在其外部可访问和可子类 定义模块.open
类成员可以访问 ,并且 定义模块之外的 overridable . -
public
类可可访问,但不可子类 定义模块.public
类成员可以访问 ,但是 在定义模块之外的不可覆盖.
- An
open
class is accessible and subclassable outside of the defining module. Anopen
class member is accessible and overridable outside of the defining module. - A
public
class is accessible but not subclassable outside of the defining module. Apublic
class member is accessible but not overridable outside of the defining module.
所以open
是public
以前的版本
Swift版本和public
的访问受到限制.
或者,就像克里斯·拉特纳(Chris Lattner)所说的那样
SE-0177:允许区分公共访问权限和公共可重写权限:
So open
is what public
used to be in previous
Swift releases and the access of public
has been restricted.
Or, as Chris Lattner puts it in
SE-0177: Allow distinguishing between public access and public overridability:
开放"现在只是比公众更公开",提供了一个非常简单和干净的模型.
"open" is now simply "more public than public", providing a very simple and clean model.
在您的示例中,open var hashValue
是可访问的属性,可以在NSObject
子类中覆盖.
In your example, open var hashValue
is a property which is accessible and can be overridden in NSObject
subclasses.
For more examples and details, have a look at SE-0117.
这篇关于Swift中的'open'关键字是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!