"""Offline Swift 5/6 semantic verification lab for Chapter 05 (data-types)."""
import json
import math
import struct
import sys
VERSION = "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)"
def case_integer_bounds_and_overflow():
bounds = {
"Int8": (-(1 << 7), (1 << 7) - 1),
"UInt8": (0, (1 << 8) - 1),
"Int16": (-(1 << 15), (1 << 15) - 1),
"Int32": (-(1 << 31), (1 << 31) - 1),
"Int64": (-(1 << 63), (1 << 63) - 1),
"UInt64": (0, (1 << 64) - 1),
}
# Wrapping addition (&+) on Int8 vs checked (+)
wrap_add_int8 = (((127 + 1) + 128) % 256) - 128
expected = {
"Int8": [-128, 127],
"UInt8": [0, 255],
"Int16": [-32768, 32767],
"Int32": [-2147483648, 2147483647],
"Int64_max": 9223372036854775807,
"Int64_min": -9223372036854775808,
"int8_wrap_127_plus_1": -128,
}
actual = {
"Int8": list(bounds["Int8"]),
"UInt8": list(bounds["UInt8"]),
"Int16": list(bounds["Int16"]),
"Int32": list(bounds["Int32"]),
"Int64_max": bounds["Int64"][1],
"Int64_min": bounds["Int64"][0],
"int8_wrap_127_plus_1": wrap_add_int8,
}
return {
"name": "integer_bounds_and_overflow",
"summary": "验证 Int8/UInt8/Int16/Int32/Int64 精确边界与溢出回绕 &+ 的补码结果",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_ieee754_float_double_precision():
double_max = sys.float_info.max
double_least_nonzero = math.nextafter(0.0, 1.0)
float32_max = struct.unpack(">f", b"\x7f\x7f\xff\xff")[0]
exact_eq = (0.1 + 0.2) == 0.3
tol_eq = abs((0.1 + 0.2) - 0.3) < 1e-12
expected = {
"double_max": 1.7976931348623157e+308,
"double_least_nonzero": 5e-324,
"double_significand_bits": 52,
"float32_max_gt_3e38": True,
"naive_01_02_eq_03": False,
"tolerance_eq_03": True,
}
actual = {
"double_max": double_max,
"double_least_nonzero": double_least_nonzero,
"double_significand_bits": sys.float_info.mant_dig - 1,
"float32_max_gt_3e38": float32_max > 3.4e38,
"naive_01_02_eq_03": exact_eq,
"tolerance_eq_03": tol_eq,
}
return {
"name": "ieee754_float_double_precision",
"summary": "核对 IEEE-754 Double/Float 边界、52 位尾数精度以及浮点容差比较语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_bool_char_string_tuple_collections():
# Character init rejects multi-character string
def make_character(s: str):
if len(s) != 1:
return {"trapped": True, "value": None}
return {"trapped": False, "value": s}
site_str = "www.bluesky" + "." + "org"
course_tuple = ("Swift 教程", 43)
langs = ["Swift", "Objective-C", "C"]
sites = {"name": "BlueSky", "url": "www.bluesky.org"}
letters = set(["a", "b", "c", "a"])
expected = {
"single_char_ok": True,
"multi_char_traps": True,
"appended_site": "www.bluesky.org",
"tuple_destructure": ["Swift 教程", 43],
"array_first": "Swift",
"dict_lookup": "BlueSky",
"set_dedup_sorted": ["a", "b", "c"],
}
actual = {
"single_char_ok": not make_character("S")["trapped"],
"multi_char_traps": make_character("AB")["trapped"],
"appended_site": site_str,
"tuple_destructure": [course_tuple[0], course_tuple[1]],
"array_first": langs[0],
"dict_lookup": sites.get("name", "未知"),
"set_dedup_sorted": sorted(letters),
}
return {
"name": "bool_char_string_tuple_collections",
"summary": "校验 Character 单字符约束、String 拼接、元组解构与 Array/Dictionary/Set 集合特性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_optional_special_types_alias_and_safety():
# Optional overview
nickname = None
first_fallback = nickname if nickname is not None else "没有昵称"
nickname = "BlueSky"
unwrapped = f"昵称是 {nickname}" if nickname is not None else ""
# Any vs AnyObject vs Never
any_items = [("BlueSky", "String"), (43, "Int"), (True, "Bool"), (9.9, "Double")]
any_object_accepts_class = True
any_object_accepts_struct = False
# typealias Distance = Double is fully identical to Double
distance_val = 9.9
explicit_sum = float(3) + 1.5
expected = {
"optional_nil_fallback": "没有昵称",
"optional_bound": "昵称是 BlueSky",
"any_runtime_types": ["String", "Int", "Bool", "Double"],
"any_object_class_only": [True, False],
"never_returns": False,
"alias_double_sum": 11.4,
"explicit_int_double_sum": 4.5,
}
actual = {
"optional_nil_fallback": first_fallback,
"optional_bound": unwrapped,
"any_runtime_types": [t for _, t in any_items],
"any_object_class_only": [any_object_accepts_class, any_object_accepts_struct],
"never_returns": False,
"alias_double_sum": round(distance_val + 1.5, 6),
"explicit_int_double_sum": explicit_sum,
}
return {
"name": "optional_special_types_alias_and_safety",
"summary": "验证 Optional 概览、Any/AnyObject/Never 语义边界、typealias 等价性与显式数值转换",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_integer_bounds_and_overflow(),
case_ieee754_float_double_precision(),
case_bool_char_string_tuple_collections(),
case_optional_special_types_alias_and_safety(),
]
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-data-types-lab/explore-data-types.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-data-types.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2094.zip
课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip