Swift扩展的访问控制

Boo*_*oon 10 access-control swift swift-extensions

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 "" }
}
Run Code Online (Sandbox Code Playgroud)

mok*_*gio 11

你的理解是正确的.

注意:public Test { }应该是public struct Test { }

放置场景3的更有趣的方法是

extension Test {
  // The exension has the same access control of Test, but this member is private
  private var prop2: String { return "" }
}
Run Code Online (Sandbox Code Playgroud)

以及

internal extension Test {
  // The compiler will throw a waning here, why would you define something public in an internal extension?
  public var prop2: String { return "" }
}
Run Code Online (Sandbox Code Playgroud)

此外,如果您觉得有趣的话,如果您的类,结构或枚举是internal,您将无法定义public扩展名.private对于您无法定义public或internal扩展的类,结构或枚举也是如此.