Swift 分机的访问控制

Access Control for Swift Extensions

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

You can extend a class, structure, or enumeration in any access context in which the class, structure, or enumeration is available. Any type members added in an extension have the same default access level as type members declared in the original type being extended. If you extend a public or internal type, any new type members you add will have a default access level of internal. If you extend a private type, any new type members you add will have a default access level of private.

Alternatively, you can mark an extension with an explicit access level modifier (for example, private extension) to set a new default access level for all members defined within the extension. This new default can still be overridden within the extension for individual type members.

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

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

你的理解基本正确。

放置场景 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 "" }
}

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