【发布时间】: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