Swift 中的“open"关键字是什么? [英] What is the 'open' keyword in Swift?

查看:39
本文介绍了Swift 中的“open"关键字是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ObjectiveC.来自标准库的 .swift 文件在第 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 类成员可访问并且可覆盖在定义模块之外.
  • public可访问,但不可子类在定义模块.public 类成员可访问,但是在定义模块之外不可覆盖.
  • An open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.
  • A public class is accessible but not subclassable outside of the defining module. A public class member is accessible but not overridable outside of the defining module.

所以 open 就是之前的 publicSwift 发布,public 的访问受到了限制.或者,正如克里斯·拉特纳所说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.

有关更多示例和详细信息,请查看 SE-0117.

For more examples and details, have a look at SE-0117.

这篇关于Swift 中的“open"关键字是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆