Swift 字符串
系统讲解 String 创建与插值、String.Index 定位与切片、常用方法与 Substring 共享存储、多行缩进与裁剪、UTF-8/UTF-16/标量三种 Unicode 视图及规范等价比较。
学完这一章,你能够
- 系统讲解 String 创建与插值、String.Index 定位与切片、常用方法与 Substring 共享存储、多行缩进与裁剪、UTF-8/UTF-16/标量三种 Unicode 视图及规范等价比较。
字符串创建、拼接、插值与 String.Index 索引
`String` 是基于 Unicode 构建的值类型有序字符集合,天然支持中文与 emoji。可通过字面量或 `String()` 构造,使用 `+`/`+=` 拼接、`\(...)` 插值(避免塞入过于复杂的表达式以保可读性),并用 `.isEmpty` 直观判空。
因不同字符占用的底层字节长度不固定,Swift 禁止用整数下标 `str[0]` 随机索引,必须借助 `String.Index` 配合 `startIndex`、`endIndex`、`index(_:offsetBy:)`、`index(after:)`、`index(before:)` 与 `distance(from:to:)` 定位和切片。务必注意 `endIndex` 指向末字符之后(非有效字符位置),取最后一个字符须用 `index(before: endIndex)`;且索引只能用于生成它的同一个字符串实例。
常用字符串方法、Substring 与多行裁剪
日常高频成员涵盖 `count`、`isEmpty`、`prefix(_:)`、`suffix(_:)`、`contains(_:)`、`hasPrefix(_:)`、`hasSuffix(_:)`、`split(separator:)`、`joined(separator:)` 以及需导入 Foundation 的 `replacingOccurrences(of:with:)`。注意现代签名 `hasPrefix(_:)`/`hasSuffix(_:)` 无外部参数标签;`split(separator:)` 默认忽略空子串(需保留则传 `omittingEmptySubsequences: false`);切片方法返回与原串共享底层缓冲区的 `Substring`,长期保存时应用 `String(sub)` 转为独立字符串。
三引号多行字符串会自动按闭合三引号行的缩进剥离各行公共前导空白;结合 Foundation 提供的 `trimmingCharacters(in:)`(支持 `.whitespacesAndNewlines`、`.whitespaces`、`.newlines`)可便捷清除首尾空白与多余换行。
Unicode 编码视图、规范等价比较与高频答疑
同一个 `String` 可分别通过 `.utf8`(UTF-8 字节序列)、`.utf16`(UTF-16 码元序列)与 `.unicodeScalars`(Unicode 标量序列)观察底层编码。由于 UTF-8 属于变长编码(一个常见汉字占 3 字节,2 个汉字在 `.utf8` 中为 6 字节,而在 `.utf16` 与 `.unicodeScalars` 中均为 2),绝不能把 `.utf8.count` 误当作字符个数;面向用户的字符遍历应直接使用 `for c in str` 或 `Array(str)`。
`==`、`!=` 与 `<`/`>` 比较遵循 Unicode 规范等价(Canonical Equivalence):例如预组合形式的 `"caf\u{00E9}"` 与拆分为字母加组合音标的 `"cafe\u{0301}"` 虽然底层标量数分别为 4 和 5,但二者扩展字素簇长度均为 4 且 `==` 判定为 `true`,开发者无需手工做 Unicode 归一化。
核心回顾:不能用 `str[0]` 是因为扩展字素簇变长无法 O(1) 定位;`count` 统计扩展字素簇而 `utf8.count` 统计字节;`hasPrefix(_:)` 不带标签;`prefix` 返回共享存储的 `Substring`;`String` 是采用写时复制优化的值类型。
Swift String 常用成员与方法速查
| 成员 | 说明 |
|---|---|
| count | 字符(扩展字素簇)个数。 |
| isEmpty | 判断是否为空字符串。 |
| prefix(n) | 截取前 n 个字符,返回 Substring。 |
| suffix(n) | 截取后 n 个字符,返回 Substring。 |
| contains(_:) | 检查是否包含指定子串或字符。 |
| hasPrefix(_:) | 检查是否以指定前缀开头(无外部标签)。 |
| hasSuffix(_:) | 检查是否以指定后缀结尾(无外部标签)。 |
| split(separator:) | 按分隔符拆分为 [Substring],默认省略空子串。 |
| joined(separator:) | 以指定分隔符连接字符串序列。 |
| replacingOccurrences(of:with:) | 替换匹配子串,需先 import Foundation。 |
离线校验 String.Index 切片、常用方法、UTF-8/16/标量视图与 Unicode 规范等价
"""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()
- 离线脚本验证索引偏移与距离、split 空子串开关、中文 UTF-8(6字节) vs UTF-16/标量(2) 差异以及 caf\u{00E9} == cafe\u{0301} 规范等价。
所需环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。
当前源码 SHA256:159f5086d16bae6862bc6b8418549a91e0227ac90c4872637a8dda4300a89069
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。
ZIP SHA256:957655a6b946e4a546b17c2cd4efc7c0f626aa37945c19c55a4ca14fcf594798
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么 Swift 切片方法 `prefix(_:)` 返回的是 `Substring` 而不是直接返回 `String`?长期持有 `Substring` 需要注意什么?
展开参考解答
`Substring` 直接引用原 `String` 的底层内存区间从而避免切片拷贝;但只要 `Substring` 存活,整段原字符串缓冲区都无法释放,因此跨作用域或长期保存时应使用 `String(sub)` 复制出独立字符串。