17

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

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

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

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

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 "" }
}
4

1 回答 1

16

你的理解几乎是正确的。

放置场景 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扩展。

于 2015-11-25T21:15:36.597 回答