"""Offline Swift 5/6 semantic verification lab for Chapter 18 (closures)."""
import json
import weakref
VERSION = "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)"
def case_closure_simplification_and_trailing_syntax():
full = lambda a, b: a + b
inferred = lambda a, b: a * b
shorthand = lambda a, b: a - b
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_asc = sorted(numbers)
evens = [n for n in numbers if n % 2 == 0]
# Multiple trailing closures
def load(source: str, on_success, on_failure):
if source.startswith("https"):
return on_success()
return on_failure()
load_ok = load("https://www.bluesky.org", lambda: "加载成功", lambda: "加载失败")
load_fail = load("http://example.org", lambda: "加载成功", lambda: "加载失败")
expected = {
"stages": [7, 12, 6],
"operator_sorted": [1, 1, 2, 3, 4, 5, 6, 9],
"trailing_evens": [4, 2, 6],
"multi_trailing": ["加载成功", "加载失败"],
}
actual = {
"stages": [full(3, 4), inferred(3, 4), shorthand(10, 4)],
"operator_sorted": sorted_asc,
"trailing_evens": evens,
"multi_trailing": [load_ok, load_fail],
}
return {
"name": "closure_simplification_and_trailing_syntax",
"summary": "验证闭包完整语法→类型推断→$0/$1 简写→运算符函数→尾随及多尾随闭包结果",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_value_capture_and_reference_type_sharing():
def make_counter():
count = 0
def inc():
nonlocal count
count += 1
return count
return inc
counter = make_counter()
seq = [counter(), counter(), counter()]
# Closures are reference types: counterA and counterB share captured box
counter_a = make_counter()
counter_b = counter_a
shared = [counter_a(), counter_b()]
expected = {"independent_seq": [1, 2, 3], "shared_reference_seq": [1, 2]}
actual = {"independent_seq": seq, "shared_reference_seq": shared}
return {
"name": "value_capture_and_reference_type_sharing",
"summary": "验证闭包捕获外层可变状态以及闭包作为引用类型在赋值后共享同一份捕获状态",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_capture_list_weak_vs_unowned_lifecycle():
events = []
class Downloader:
def __init__(self):
self.site = "BlueSky"
self.on_finish = None
def start(self):
self_ref = weakref.ref(self)
def cb():
obj = self_ref()
if obj is None:
return
events.append(f"下载完成:{obj.site}")
self.on_finish = cb
def __del__(self):
events.append("Downloader 被释放")
d = Downloader()
d.start()
d.on_finish()
saved_cb = d.on_finish
del d # refcount drops to 0 immediately because closure holds weakref, no retain cycle
saved_cb() # self is nil -> safely returns without crashing
# [unowned self] model: accesses directly while alive, traps if accessed after deallocation
class TimerOwner:
def __init__(self):
self.seconds = 0
ref = weakref.ref(self)
def tick():
obj = ref()
if obj is None:
raise RuntimeError("Fatal error: Attempted to read an unowned reference but object was already deallocated")
obj.seconds += 1
return obj.seconds
self.tick = tick
owner = TimerOwner()
ticks = [owner.tick(), owner.tick()]
dangling_tick = owner.tick
del owner
unowned_trapped = False
try:
dangling_tick()
except RuntimeError:
unowned_trapped = True
expected = {
"weak_events": ["下载完成:BlueSky", "Downloader 被释放"],
"unowned_ticks": [1, 2],
"unowned_after_deinit_traps": True,
}
actual = {
"weak_events": events,
"unowned_ticks": ticks,
"unowned_after_deinit_traps": unowned_trapped,
}
return {
"name": "capture_list_weak_vs_unowned_lifecycle",
"summary": "通过 weakref 实测 [weak self] 打破循环引用安全释放与 [unowned self] 悬垂访问陷阱",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_nonescaping_vs_escaping_lifetime():
trace = []
def perform(action):
action()
trace.append("perform 返回前已结束")
class Store:
def __init__(self):
self.stored = None
def save(self, action):
self.stored = action
trace.append("save 已返回,闭包尚未执行")
perform(lambda: trace.append("非逃逸闭包立即执行"))
s = Store()
s.save(lambda: trace.append("逃逸闭包稍后执行"))
s.stored()
expected = {
"trace": [
"非逃逸闭包立即执行",
"perform 返回前已结束",
"save 已返回,闭包尚未执行",
"逃逸闭包稍后执行",
]
}
actual = {"trace": trace}
return {
"name": "nonescaping_vs_escaping_lifetime",
"summary": "验证非逃逸闭包在函数返回前同步执行完毕与 @escaping 逃逸闭包跨调用存活的时序差异",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_closure_simplification_and_trailing_syntax(),
case_value_capture_and_reference_type_sharing(),
case_capture_list_weak_vs_unowned_lifecycle(),
case_nonescaping_vs_escaping_lifetime(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。
入口文件:projects/swift-closures-lab/explore-closures.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-closures.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2091.zip
课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip