Swift编程语言有关于扩展的访问控制的说法:
您可以在任何访问中扩展类,结构或枚举 类,结构或枚举可用的上下文。 在扩展中添加的任何类型成员都具有相同的默认访问权限 level作为在扩展的原始类型中声明的类型成员。如果 您扩展公共或内部类型,您添加的任何新类型成员 将具有内部的默认访问级别。如果你扩展私人 类型,您添加的任何新类型成员将具有默认访问级别 私有的。
或者,您可以使用显式访问级别标记扩展名 修饰符(例如,私有扩展名)以设置新的默认访问权限 扩展中定义的所有成员的级别。这个新的默认值 仍然可以在个人类型的扩展名中覆盖 成员。
我不完全理解上述说法。是说以下内容:
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 "" }
}
答案 0 :(得分:8)
您的理解是正确的。
注意: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 "" }
}
以及
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 "" }
}
另外,如果您感兴趣的话,如果您的类,结构或枚举为internal
,您将无法定义public
扩展名。同样适用于private
类,结构或枚举,您无法为其定义public
或internal
扩展名。