"""Offline Swift 5/6 semantic verification lab for Chapter 13 (strings)."""
import json
import unicodedata
VERSION = "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)"
def grapheme_clusters(s: str):
"""Minimal deterministic Extended Grapheme Cluster splitter covering combining marks & ZWJ/skin-tone emoji."""
clusters = []
i = 0
n = len(s)
while i < n:
buf = s[i]
i += 1
while i < n:
ch = s[i]
cat = unicodedata.category(ch)
cp = ord(ch)
if cat in ("Mn", "Me") or (0x1F3FB <= cp <= 0x1F3FF):
buf += ch
i += 1
elif cp == 0x200D and i + 1 < n:
buf += ch + s[i + 1]
i += 2
else:
break
clusters.append(buf)
return clusters
def case_creation_concat_interpolation_and_indices():
site = "www.bluesky.org"
clusters = grapheme_clusters(site)
# String.Index simulation bound to owner string id
start = 0
end = len(clusters)
fourth = start + 3
i4, i11 = start + 4, start + 11
sub = "".join(clusters[i4:i11])
empty_a = ""
empty_b = str()
expected = {
"empty_checks": [True, True],
"concat_interp": "20 乘于 100 等于 2000",
"fourth_char": ".",
"slice_4_11": "bluesky",
"distance": 7,
"start_after_before_end": ["w", "w", "g"],
}
actual = {
"empty_checks": [len(empty_a) == 0, len(empty_b) == 0],
"concat_interp": f"{20} 乘于 100 等于 {20 * 100}",
"fourth_char": clusters[fourth],
"slice_4_11": sub,
"distance": i11 - i4,
"start_after_before_end": [clusters[start], clusters[start + 1], clusters[end - 1]],
}
return {
"name": "creation_concat_interpolation_and_indices",
"summary": "验证空串判断、字符串拼接与插值以及 String.Index (startIndex/endIndex/offsetBy/distance) 定位",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_string_methods_substring_and_trimming():
site = "www.bluesky.org"
csv = "Alpha,Beta,Swift"
parts_default = [p for p in csv.split(",") if p != ""]
parts_keep_empty = "a,,b".split(",")
parts_omit_empty = [p for p in "a,,b".split(",") if p != ""]
joined = " | ".join(parts_default)
replaced = site.replace("bluesky", "BLUESKY")
raw_lines = [" BlueSky", " www.bluesky.org", "", " "]
raw_text = "\n".join(line[4:] if line.startswith(" ") else line for line in raw_lines[:-1])
trimmed = raw_text.strip()
expected = {
"count": 15,
"prefix3": "www",
"suffix3": "org",
"contains": True,
"has_prefix_suffix": [True, True],
"split_default_count": 3,
"split_omit_vs_keep": [["a", "b"], ["a", "", "b"]],
"joined": "Alpha | Beta | Swift",
"replaced": "www.BLUESKY.org",
"trimmed": "BlueSky\nwww.bluesky.org",
}
actual = {
"count": len(grapheme_clusters(site)),
"prefix3": site[:3],
"suffix3": site[-3:],
"contains": "bluesky" in site,
"has_prefix_suffix": [site.startswith("www"), site.endswith("org")],
"split_default_count": len(parts_default),
"split_omit_vs_keep": [parts_omit_empty, parts_keep_empty],
"joined": joined,
"replaced": replaced,
"trimmed": trimmed,
}
return {
"name": "string_methods_substring_and_trimming",
"summary": "校验 prefix/suffix、hasPrefix(_:)/hasSuffix(_:)、split 丢弃空子串策略、替换与多行裁剪",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_unicode_views_utf8_utf16_scalars():
text = "蓝天"
utf8_bytes = list(text.encode("utf-8"))
utf16_bytes = text.encode("utf-16-le")
utf16_units = [int.from_bytes(utf16_bytes[i:i + 2], "little") for i in range(0, len(utf16_bytes), 2)]
scalars = [ord(c) for c in text]
clusters = grapheme_clusters(text)
expected = {
"grapheme_count": 2,
"utf8_count": 6,
"utf16_count": 2,
"scalar_count": 2,
"utf8_bytes": [232, 147, 157, 229, 164, 169],
"scalars": [34013, 22825],
}
actual = {
"grapheme_count": len(clusters),
"utf8_count": len(utf8_bytes),
"utf16_count": len(utf16_units),
"scalar_count": len(scalars),
"utf8_bytes": utf8_bytes,
"scalars": scalars,
}
return {
"name": "unicode_views_utf8_utf16_scalars",
"summary": "对比中文字符串在扩展字素簇(count)、UTF-8 字节视图、UTF-16 码元视图与 Unicode 标量视图的数量差异",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_canonical_equivalence_comparison():
cafe1 = "caf\u00E9"
cafe2 = "cafe\u0301"
swift_eq = unicodedata.normalize("NFC", cafe1) == unicodedata.normalize("NFC", cafe2)
cmp_a, cmp_b = "Hello, Swift!", "Hello, World!"
expected = {
"cmp_eq_ne_lt": [False, True, True],
"canonical_equal": True,
"cafe1_grapheme_count": 4,
"cafe2_grapheme_count": 4,
"cafe1_vs_cafe2_scalar_counts": [4, 5],
}
actual = {
"cmp_eq_ne_lt": [cmp_a == cmp_b, cmp_a != cmp_b, cmp_a < cmp_b],
"canonical_equal": swift_eq,
"cafe1_grapheme_count": len(grapheme_clusters(cafe1)),
"cafe2_grapheme_count": len(grapheme_clusters(cafe2)),
"cafe1_vs_cafe2_scalar_counts": [len(cafe1), len(cafe2)],
}
return {
"name": "canonical_equivalence_comparison",
"summary": "验证 Unicode 规范等价比较(caf\\u{00E9} == cafe\\u{0301})及两者扩展字素簇长度均为 4",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_creation_concat_interpolation_and_indices(),
case_string_methods_substring_and_trimming(),
case_unicode_views_utf8_utf16_scalars(),
case_canonical_equivalence_comparison(),
]
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-strings-lab/explore-strings.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-strings.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2123.zip