Swift 访问控制
系统核对 Swift 现代六个访问级别(private、fileprivate、internal、package、public、open)、private(set) 读写分离、无 protected 设计原因、隐式构造器可见性及扩展默认访问级别。
学完这一章,你能够
- 系统核对 Swift 现代六个访问级别(private、fileprivate、internal、package、public、open)、private(set) 读写分离、无 protected 设计原因、隐式构造器可见性及扩展默认访问级别。
六个访问级别总览与文件/模块边界
访问控制决定不同作用域、源文件、模块及包之间谁可以引用、继承或重写代码。现代 Swift 共有六个访问级别,由严到宽依次为 `private`、`fileprivate`、`internal`、`package`(Swift 5.9 引入,SE-0386)、`public` 与 `open`。需纠正两类陈旧误解:第一,`open` 才是最高级别且仅适用于类及类成员;第二,`package` 介于 `internal` 与 `public` 之间,专门服务于同一 Swift Package 内多模块协作。
`private` 的作用域自 Swift 4 起并非“仅限大括号内部”,而是“声明所在词法作用域 + 同一源文件内该类型的扩展”(如 `User` 的同文件扩展可直接读取 `private var token` 生成脱敏字符串,但拆分到另一文件后即不可见)。`fileprivate` 将可见性放宽到整个 `.swift` 文件内的所有类型(如 `Logger` 访问同文件 `User` 的 `site`)。未标注修饰符时默认 `internal`,可见范围为一个编译模块(App target、framework 或 SwiftPM target);跨模块规则须在多 target 包中验证。
跨模块级别:package、public 与 open
同一 Swift Package 内包含多个 target(如库模块 `CoreKit` 与可执行模块 `AppCLI`)时,用 `package` 修饰的函数或类型可在同包各模块间自由共享,但对包外调用方完全隐藏(依赖该包的外部工程会报找不到符号)。需特别注意:`package` 仅放宽可见性,不授予跨模块继承权,跨模块继承仍必须使用 `open`。构建时 SwiftPM 会自动传递 `-package-name` 界定包边界,手工调用 `swiftc` 需自行补传该参数。
`public` 允许任意外部模块使用,但禁止模块外继承类或重写成员,便于框架作者安全演进内部实现。唯有 `open` 允许跨模块继承类及重写成员(不可用于结构体、枚举与协议);且即使类本身为 `open`,其内部标为 `public` 的方法在模块外仍不可重写,仅标为 `open` 的方法才可被外部子类 `override`。
private(set)、无 protected 哲学与构造器/扩展可见性
通过 `private(set)`(或更一般的 `fileprivate(set)`、`internal(set)`)可把属性读取与写入权限分离:getter 维持外层访问级别(外部可读 `visitCount`),setter 则收紧至括号内级别,外部赋值直接触发编译错误 `setter is inaccessible`,极其适合状态与计数属性。
Swift 刻意不提供 C++/Java 的 `protected`,因为 Swift 访问控制按“文件 / 模块 / 包”组织而非“类继承层次”;大量值类型与协议扩展根本不存在类继承,且 `protected` 容易造成父子类紧耦合,Swift 鼓励改用 `internal`/`fileprivate` 与协议组合隔离内部细节。
构造器可见性最易踩的坑在于:`public struct` 自动合成的成员逐一构造器默认仍是 `internal`,跨模块构造会报错,必须显式编写 `public init`;反之将构造器设为 `private init()` 并配 `static let shared` 是经典的单例防误实例化写法。扩展本身亦可携带默认访问级别(如 `public extension`),其成员可覆盖该默认级别但最高不得超过被扩展类型自身的可见性;同文件多个扩展之间同样共享 `private` 成员。
访问控制常见问题
五项速查结论:成员实际可见性不能高于所在类型(`internal` 类型里的 `public` 成员实际仍是 `internal`);对外 API 默认选 `public`,确需扩展点才开放 `open`;`internal` 止于单 target,`package` 覆盖同包全部 target;`private(set)` 不影响 getter 级别;`public` 类跨模块不可继承须升级为 `open` 且可重写成员同步标 `open`。本站离线矩阵校验器已对六个级别 × 六类调用上下文完成全量核验。
Swift 六个访问级别可见性与继承权限对照
| 级别 | 可见范围 | 能否跨模块 | 能否跨模块继承或重写 |
| private | 声明所在作用域 + 同文件内该类型的扩展 | 否 | 否 |
| fileprivate | 声明所在的整个 .swift 源文件 | 否 | 否 |
| internal | 声明所在的单个模块(默认访问级别) | 否 | 否 |
| package | 同一 Swift Package 内的全部模块 | 同包内可以 | 否,仍需 open |
| public | 任意模块 | 是 | 否 |
| open | 任意模块(仅限类及类成员) | 是 | 是 |
运行离线 Python 校验:Swift 六级访问矩阵、private(set)、package/open 边界与构造器可见性
展开查看收起
"""Offline CPython 3.12.14 semantic verifier for Swift Access Control (CH34)."""
import json
from dataclasses import dataclass
@dataclass(frozen=True)
class SiteContext:
package: str
module: str
file: str
scope: str
is_extension_of_same_type: bool = False
@dataclass(frozen=True)
class DeclContext:
level: str # private, fileprivate, internal, package, public, open
package: str
module: str
file: str
scope: str
is_class_or_member: bool = True
def can_access(decl: DeclContext, caller: SiteContext) -> bool:
lvl = decl.level
if lvl == "private":
return caller.file == decl.file and (
caller.scope == decl.scope or caller.is_extension_of_same_type
)
if lvl == "fileprivate":
return caller.file == decl.file
if lvl == "internal":
return caller.module == decl.module
if lvl == "package":
return caller.package == decl.package
if lvl in ("public", "open"):
return True
raise ValueError(f"Unknown level {lvl}")
def can_subclass_or_override(decl: DeclContext, caller: SiteContext) -> bool:
if not decl.is_class_or_member:
return False
if caller.module == decl.module:
return can_access(decl, caller)
return decl.level == "open"
def case_six_level_visibility_matrix():
decl_base = dict(package="PkgA", module="CoreKit", file="Core.swift", scope="User")
callers = {
"same_scope": SiteContext("PkgA", "CoreKit", "Core.swift", "User"),
"same_file_ext": SiteContext("PkgA", "CoreKit", "Core.swift", "UserExt", is_extension_of_same_type=True),
"same_file_other": SiteContext("PkgA", "CoreKit", "Core.swift", "Logger"),
"same_module": SiteContext("PkgA", "CoreKit", "Other.swift", "Service"),
"same_pkg_other_mod": SiteContext("PkgA", "AppCLI", "main.swift", "Main"),
"external_pkg": SiteContext("PkgB", "ThirdParty", "ext.swift", "Client"),
}
levels = ["private", "fileprivate", "internal", "package", "public", "open"]
access_matrix = {}
override_ext = {}
for lv in levels:
d = DeclContext(level=lv, **decl_base)
access_matrix[lv] = [can_access(d, callers[k]) for k in callers]
override_ext[lv] = can_subclass_or_override(d, callers["same_pkg_other_mod"])
actual = {"access_matrix": access_matrix, "cross_module_override": override_ext}
expected = {
"access_matrix": {
"private": [True, True, False, False, False, False],
"fileprivate": [True, True, True, False, False, False],
"internal": [True, True, True, True, False, False],
"package": [True, True, True, True, True, False],
"public": [True, True, True, True, True, True],
"open": [True, True, True, True, True, True],
},
"cross_module_override": {
"private": False,
"fileprivate": False,
"internal": False,
"package": False,
"public": False,
"open": True,
},
}
return {
"name": "six_level_visibility_matrix",
"summary": "Verify Swift 6-level access control matrix across scope, same-file extension, file, module, package, and external package.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_private_set_and_extension_visibility():
getter_decl = DeclContext("internal", "PkgA", "CoreKit", "User.swift", "User")
setter_decl = DeclContext("private", "PkgA", "CoreKit", "User.swift", "User")
inside = SiteContext("PkgA", "CoreKit", "User.swift", "User")
outside_same_mod = SiteContext("PkgA", "CoreKit", "Other.swift", "Caller")
same_file_ext = SiteContext("PkgA", "CoreKit", "User.swift", "UserExt2", is_extension_of_same_type=True)
other_file_ext = SiteContext("PkgA", "CoreKit", "UserExtra.swift", "UserExt3", is_extension_of_same_type=True)
token = "SWIFT-SECRET"
masked = token[:3] + "****"
visit_count = 0
if can_access(setter_decl, inside):
visit_count += 1
visit_count += 1
actual = {
"external_can_read_visit_count": can_access(getter_decl, outside_same_mod),
"external_can_write_visit_count": can_access(setter_decl, outside_same_mod),
"internal_visit_count": visit_count,
"masked_token_in_same_file_ext": masked if can_access(setter_decl, same_file_ext) else None,
"other_file_ext_can_access_private": can_access(setter_decl, other_file_ext),
}
expected = {
"external_can_read_visit_count": True,
"external_can_write_visit_count": False,
"internal_visit_count": 2,
"masked_token_in_same_file_ext": "SWI****",
"other_file_ext_can_access_private": False,
}
return {
"name": "private_set_and_extension_visibility",
"summary": "Verify private(set) allows external reads while restricting writes, and Swift 4+ private shares across same-file extensions only.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_package_public_open_cross_module():
app = SiteContext("PkgA", "AppCLI", "main.swift", "Main")
ext = SiteContext("PkgB", "External", "main.swift", "Main")
open_cls = DeclContext("open", "PkgA", "CoreKit", "Kit.swift", "Base")
pub_cls = DeclContext("public", "PkgA", "CoreKit", "Kit.swift", "Helper")
pub_member_on_open = DeclContext("public", "PkgA", "CoreKit", "Kit.swift", "Base.helperMethod")
pkg_fn = DeclContext("package", "PkgA", "CoreKit", "Kit.swift", "internalName", is_class_or_member=False)
actual = {
"app_can_subclass_open": can_subclass_or_override(open_cls, app),
"app_can_subclass_public": can_subclass_or_override(pub_cls, app),
"app_can_override_public_in_open_class": can_subclass_or_override(pub_member_on_open, app),
"app_can_call_package_fn": can_access(pkg_fn, app),
"ext_pkg_can_call_package_fn": can_access(pkg_fn, ext),
}
expected = {
"app_can_subclass_open": True,
"app_can_subclass_public": False,
"app_can_override_public_in_open_class": False,
"app_can_call_package_fn": True,
"ext_pkg_can_call_package_fn": False,
}
return {
"name": "package_public_open_cross_module",
"summary": "Verify cross-module open subclassing, public non-subclassable boundary, and package-level intra-package sharing.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_initializer_visibility_and_singleton():
app = SiteContext("PkgA", "AppCLI", "main.swift", "Main")
implicit_memberwise_init = DeclContext("internal", "PkgA", "CoreKit", "Kit.swift", "PublicStruct.init", is_class_or_member=False)
explicit_public_init = DeclContext("public", "PkgA", "CoreKit", "Kit.swift", "PublicStruct.init", is_class_or_member=False)
singleton_init = DeclContext("private", "PkgA", "CoreKit", "Config.swift", "AppConfig.init", is_class_or_member=False)
singleton_shared = DeclContext("public", "PkgA", "CoreKit", "Config.swift", "AppConfig.shared", is_class_or_member=False)
actual = {
"implicit_struct_init_cross_module": can_access(implicit_memberwise_init, app),
"explicit_public_init_cross_module": can_access(explicit_public_init, app),
"singleton_direct_init_external": can_access(singleton_init, app),
"singleton_shared_accessible": can_access(singleton_shared, app),
}
expected = {
"implicit_struct_init_cross_module": False,
"explicit_public_init_cross_module": True,
"singleton_direct_init_external": False,
"singleton_shared_accessible": True,
}
return {
"name": "initializer_visibility_and_singleton",
"summary": "Verify synthesized public struct memberwise init stays internal cross-module and private init enforces singleton access.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main() -> None:
report = {
"version": "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)",
"cases": [
case_six_level_visibility_matrix(),
case_private_set_and_extension_visibility(),
case_package_public_open_cross_module(),
case_initializer_visibility_and_singleton(),
],
}
print(json.dumps(report, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
因为编译器为结构体自动合成的成员逐一构造器最高只有 internal 访问级别,不会随结构体自动提升为 public;必须显式编写一个 public init(...)。