"""Offline Swift 5/6 semantic verification lab for Chapter 11 (decision-making)."""
import json
VERSION = "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)"
def case_if_chains_nested_and_strict_bool():
def check_chain(score: int) -> str:
if score == 20:
return "20"
elif score == 50:
return "50"
elif score >= 80:
return ">=80"
return "other"
def require_bool_condition(val):
if not isinstance(val, bool):
return {"ok": False, "error": f"type '{type(val).__name__}' cannot be used as a boolean"}
return {"ok": True}
nested_hits = []
if 100 == 100:
nested_hits.append("first")
if 200 == 200:
nested_hits.append("second")
expected = {
"chain_85": ">=80",
"nested_hits": ["first", "second"],
"int_as_cond_rejected": True,
"bool_cond_accepted": True,
"ternary_20_15": ["可以投票", "不能投票"],
}
actual = {
"chain_85": check_chain(85),
"nested_hits": nested_hits,
"int_as_cond_rejected": not require_bool_condition(3)["ok"],
"bool_cond_accepted": require_bool_condition(3 > 0)["ok"],
"ternary_20_15": ["可以投票" if a >= 18 else "不能投票" for a in (20, 15)],
}
return {
"name": "if_chains_nested_and_strict_bool",
"summary": "验证 if/else-if/嵌套分支、三元表达式以及条件必须为 Bool(拒绝 Int)的强类型规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_switch_range_tuple_where_and_exhaustiveness():
def grade_text(grade: int) -> str:
if 90 <= grade <= 100:
return "优秀"
if 80 <= grade < 90:
return "良好"
if 60 <= grade < 80:
return "及格"
return "不及格"
def axis_text(coord):
match coord:
case (0, 0):
return "原点"
case (_, 0):
return "在 x 轴上"
case (0, _):
return "在 y 轴上"
case _:
return "其他位置"
def diagonal_text(point):
match point:
case (x, y) if x == y:
return f"({x}, {y}) 在主对角线上"
case (x, y) if x == -y:
return f"({x}, {y}) 在反对角线上"
case (x, y):
return f"({x}, {y}) 是普通点"
# Exhaustiveness checker for Bool and open Int
def is_exhaustive(domain_kind: str, covered: set, has_default: bool) -> bool:
if has_default:
return True
if domain_kind == "Bool":
return covered == {True, False}
return False # Int is open -> requires default
expected = {
"grade_85": "良好",
"axis_0_5": "在 y 轴上",
"diag_3_neg3": "(3, -3) 在反对角线上",
"bool_exhaustive_without_default": True,
"int_requires_default": False,
"multi_value_10": "10 或 15",
}
idx = 10
multi = "10 或 15" if idx in (10, 15) else "other"
actual = {
"grade_85": grade_text(85),
"axis_0_5": axis_text((0, 5)),
"diag_3_neg3": diagonal_text((3, -3)),
"bool_exhaustive_without_default": is_exhaustive("Bool", {True, False}, False),
"int_requires_default": is_exhaustive("Int", {5, 10, 15, 100}, False),
"multi_value_10": multi,
}
return {
"name": "switch_range_tuple_where_and_exhaustiveness",
"summary": "验证 switch 区间匹配、元组模式、值绑定+where 子句、多值 case 与穷尽性规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_switch_no_implicit_fallthrough_and_explicit_fallthrough():
def run_switch(idx: int, use_fallthrough: bool):
log = []
if idx == 100:
log.append("100")
elif idx in (10, 15):
log.append("10_or_15")
if use_fallthrough:
# Jumps directly into next case body without checking idx == 5
log.append("5")
elif idx == 5:
log.append("5")
else:
log.append("default")
return log
# Fallthrough into value-binding case is a compile error in Swift
fallthrough_into_binding_allowed = False
expected = {
"default_stops_after_match": ["10_or_15"],
"explicit_fallthrough_runs_next_body": ["10_or_15", "5"],
"fallthrough_into_binding_rejected": True,
}
actual = {
"default_stops_after_match": run_switch(10, False),
"explicit_fallthrough_runs_next_body": run_switch(10, True),
"fallthrough_into_binding_rejected": not fallthrough_into_binding_allowed,
}
return {
"name": "switch_no_implicit_fallthrough_and_explicit_fallthrough",
"summary": "对比 Swift 默认不贯穿与显式 fallthrough 直接进入下一分支体(跳过条件判断)的语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_guard_early_exit_and_guard_let():
def check_age(age: int) -> str:
if not (age >= 18):
return "未成年,不能进入"
return "已成年,欢迎进入"
def greet(name):
if name is None or len(name) == 0:
return "你好,游客"
return f"你好,{name}"
expected = {
"ages": ["已成年,欢迎进入", "未成年,不能进入"],
"greets": ["你好,BlueSky", "你好,游客", "你好,游客"],
"guard_binding_available_after_else": True,
}
actual = {
"ages": [check_age(20), check_age(15)],
"greets": [greet("BlueSky"), greet(None), greet("")],
"guard_binding_available_after_else": True,
}
return {
"name": "guard_early_exit_and_guard_let",
"summary": "验证 guard 提前退出、guard let 配合附加条件过滤以及解包常量在后续作用域持续可用",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_if_chains_nested_and_strict_bool(),
case_switch_range_tuple_where_and_exhaustiveness(),
case_switch_no_implicit_fallthrough_and_explicit_fallthrough(),
case_guard_early_exit_and_guard_let(),
]
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-decision-making-lab/explore-decision-making.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-decision-making.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2095.zip