蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 Optional<T> 枚举模型、强制解包陷阱、if/guard let 与 ?? 链式求值

PYTHONWindows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。explore-optionals.py
explore-optionals.py196 行
"""Offline Swift 5/6 semantic verification lab for Chapter 07 (optionals)."""
import json

VERSION = "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)"


class SwiftOptional:
    """Models Swift Optional<T> enum with .some(value) and .none."""

    def __init__(self, wrapped_type: str, has_value: bool = False, value=None):
        self.wrapped_type = wrapped_type
        self.case = "some" if has_value else "none"
        self.value = value if has_value else None

    @classmethod
    def some(cls, wrapped_type: str, value):
        return cls(wrapped_type, True, value)

    @classmethod
    def none(cls, wrapped_type: str):
        return cls(wrapped_type, False, None)

    def format_print(self) -> str:
        if self.case == "none":
            return "nil"
        if isinstance(self.value, str):
            return f'Optional("{self.value}")'
        return f"Optional({self.value})"

    def force_unwrap(self):
        if self.case == "none":
            raise RuntimeError("Fatal error: Unexpectedly found nil while unwrapping an Optional value")
        return self.value

    def nil_coalesce(self, default_val):
        return self.value if self.case == "some" else default_val

    def __eq__(self, other):
        if isinstance(other, SwiftOptional):
            return self.case == other.case and self.value == other.value
        if other is None:
            return self.case == "none"
        return self.case == "some" and self.value == other


def case_optional_enum_representation_and_nil_bool_rule():
    a = SwiftOptional.some("Int", 42)
    b = SwiftOptional.some("Int", 42)
    c = SwiftOptional.none("Int")
    uninitialized_site = SwiftOptional.none("String")
    nums = SwiftOptional.some("[Int]", [1, 2, 3])
    nums_nil = SwiftOptional.none("[Int]")

    # Condition check: Swift rejects Optional as Bool
    def check_condition_type(expr):
        if isinstance(expr, SwiftOptional):
            return {"ok": False, "error": f"optional type '{expr.wrapped_type}?' cannot be used as a boolean"}
        return {"ok": isinstance(expr, bool)}

    cond_err = check_condition_type(SwiftOptional.some("String", "www.bluesky.org"))
    cond_ok = check_condition_type(a != None)  # noqa: E711
    expected = {
        "prints": ["Optional(42)", "Optional(42)", "nil", "nil", "Optional([1, 2, 3])", "nil"],
        "optional_as_bool_rejected": True,
        "explicit_neq_nil_ok": True,
        "nil_to_non_optional_bool_rejected": True,
    }
    actual = {
        "prints": [a.format_print(), b.format_print(), c.format_print(), uninitialized_site.format_print(), nums.format_print(), nums_nil.format_print()],
        "optional_as_bool_rejected": not cond_err["ok"],
        "explicit_neq_nil_ok": cond_ok["ok"],
        "nil_to_non_optional_bool_rejected": not isinstance(None, bool),
    }
    return {
        "name": "optional_enum_representation_and_nil_bool_rule",
        "summary": "验证 Optional<T> (.some/.none) 枚举模型、打印格式以及 nil 不能作为 Bool 条件的规则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_forced_unwrap_and_fatal_trap():
    present = SwiftOptional.some("String", "www.bluesky.org")
    absent = SwiftOptional.none("String")
    val = present.force_unwrap()
    trapped_msg = ""
    try:
        absent.force_unwrap()
    except RuntimeError as exc:
        trapped_msg = str(exc)
    expected = {
        "unwrapped": "www.bluesky.org",
        "nil_trap_triggered": True,
        "trap_contains_unexpectedly_found_nil": True,
    }
    actual = {
        "unwrapped": val,
        "nil_trap_triggered": bool(trapped_msg),
        "trap_contains_unexpectedly_found_nil": "Unexpectedly found nil" in trapped_msg,
    }
    return {
        "name": "forced_unwrap_and_fatal_trap",
        "summary": "校验强制解包 ! 在有值时提取原值、在 nil 时触发运行时 Fatal error 陷阱",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_optional_binding_if_let_guard_let_shorthand():
    def guard_describe(opt: SwiftOptional) -> str:
        if opt.case == "none":
            return "值为 nil,直接返回"
        text = opt.value
        return f"guard let 解包成功:{text},长度 {len(text)}"

    def multi_bind(site: SwiftOptional, tag: SwiftOptional) -> str:
        if site.case == "some" and tag.case == "some":
            return f"{site.value} - {tag.value}"
        return "至少有一个为 nil"

    s = SwiftOptional.some("String", "www.bluesky.org")
    t_some = SwiftOptional.some("Int", 2026)
    t_none = SwiftOptional.none("Int")
    expected = {
        "guard_some": "guard let 解包成功:BlueSky,长度 7",
        "guard_none": "值为 nil,直接返回",
        "multi_both_some": "www.bluesky.org - 2026",
        "multi_one_nil": "至少有一个为 nil",
    }
    actual = {
        "guard_some": guard_describe(SwiftOptional.some("String", "BlueSky")),
        "guard_none": guard_describe(SwiftOptional.none("String")),
        "multi_both_some": multi_bind(s, t_some),
        "multi_one_nil": multi_bind(s, t_none),
    }
    return {
        "name": "optional_binding_if_let_guard_let_shorthand",
        "summary": "验证 if let、guard let 提前退出以及 Swift 5.7+ 简写多条件绑定语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_nil_coalescing_and_iuo():
    site_nil = SwiftOptional.none("String")
    site_val = SwiftOptional.some("String", "BlueSky")
    a = SwiftOptional.none("Int")
    b = SwiftOptional.none("Int")
    chained = a.nil_coalesce(b.nil_coalesce(0))
    # IUO T! behaves like Optional that auto-force-unwraps on access
    iuo_present = SwiftOptional.some("String", "蓝色天空")
    iuo_nil = SwiftOptional.none("String")
    iuo_nil_traps = False
    try:
        _ = len(iuo_nil.force_unwrap())
    except RuntimeError:
        iuo_nil_traps = True
    expected = {
        "coalesce_nil": "www.bluesky.org",
        "coalesce_some": "BlueSky",
        "chained_coalesce": 0,
        "iuo_present_count": 4,
        "iuo_nil_traps": True,
    }
    actual = {
        "coalesce_nil": site_nil.nil_coalesce("www.bluesky.org"),
        "coalesce_some": site_val.nil_coalesce("默认值"),
        "chained_coalesce": chained,
        "iuo_present_count": len(iuo_present.force_unwrap()),
        "iuo_nil_traps": iuo_nil_traps,
    }
    return {
        "name": "nil_coalescing_and_iuo",
        "summary": "验证链式空合运算符 ?? 求值与隐式解包可选类型 T! 访问行为及空值崩溃风险",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_optional_enum_representation_and_nil_bool_rule(),
        case_forced_unwrap_and_fatal_trap(),
        case_optional_binding_if_let_guard_let_shorthand(),
        case_nil_coalescing_and_iuo(),
    ]
    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-optionals-lab/explore-optionals.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-optionals.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Swift

课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip

下载课程关联工程包:Swift

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2115.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习