【问题标题】:Access Control for Swift ExtensionsSwift 扩展的访问控制
【发布时间】:2020-02-05 18:26:18
【问题描述】:

Swift 编程语言对扩展的访问控制有这样的说法:

您可以在任何访问中扩展类、结构或枚举 类、结构或枚举可用的上下文。 在扩展中添加的任何类型成员都具有相同的默认访问权限 级别作为在被扩展的原始类型中声明的类型成员。如果 您扩展公共或内部类型,您添加的任何新类型成员 将具有内部的默认访问级别。如果您扩展私人 类型,您添加的任何新类型成员都将具有默认访问级别 私人的。

或者,您可以使用显式访问级别标记扩展 修饰符(例如,私有扩展)设置新的默认访问 扩展中定义的所有成员的级别。这个新的默认值 仍然可以在单个类型的扩展中被覆盖 成员。

我不完全理解上面的说法。是不是在说:

public struct Test { }

extension Test {
  // 1. This will be default to internal because Test is public?
  var prop: String { return "" }
}

public extension Test {
  // 2. This will have access level of public because extension is marked public?
  var prop2: String { return "" }

extension Test {
  // 3. Is this the same as the above public extension example?
  public var prop2: String { return "" }
}

【问题讨论】:

  • 我认为prop2 的定义与Apple Document 冲突:If you extend a public or internal type, any new type members you add will have a default access level of internal. 还是我理解错了?

标签: swift access-control swift-extensions


【解决方案1】:

你的理解几乎是正确的。

一个更有趣的方式来放置你的场景 3 是

extension Test {
  // The extension has access control internal, because of what the docs say:
  //
  // > If you extend a public or internal type, any new type members you add
  // > will have a default access level of internal.
  //
  // Despite the extension being internal, this member is private because it's
  // declared explicitly here.
  private var prop2: String { return "" }
}

还有

internal extension Test {
  // The compiler will give a waning here, why would you define something public
  // in an internal extension?
  public var prop2: String { return "" }
}

此外,如果您的类、结构或枚举是 internal,您可能会发现有趣的是,您将无法定义 public 扩展。 private 类、结构或枚举也是如此,您不能为其定义 publicinternal 扩展。

【讨论】:

  • "//exension和Test一样的访问控制。它不应该是内部的吗,根据“如果您扩展公共或内部类型,您添加的任何新类型成员都将具有内部的默认访问级别。”
  • 感谢@BangOperator,您确实是正确的。我已经更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-12
  • 1970-01-01
  • 1970-01-01
  • 2015-06-21
  • 1970-01-01
  • 2022-06-11
相关资源
最近更新 更多