Swift 教程
概述 Swift 多范式编译型语言定位、适用读者、首个 Hello World 变量输出示例及官方语言指南与 Swift Evolution 提案参考入口。
学完这一章,你能够
- 概述 Swift 多范式编译型语言定位、适用读者、首个 Hello World 变量输出示例及官方语言指南与 Swift Evolution 提案参考入口。
Swift 语言定位与学习对象
Swift 是 Apple 于 2014 年 WWDC 推出的开源通用编译型编程语言,支持面向过程、面向对象、函数式与面向协议等多编程范式,广泛用于 iOS、iPadOS、macOS、watchOS 与 tvOS 应用开发。它融合了 C 与 Objective-C 的工程经验,同时摆脱了 C 语言历史兼容包袱;在 Apple 平台上可与 Objective-C 共用同一套运行时环境并顺畅互操作。
本系列教程面向希望切入移动端与 Apple 桌面应用开发的程序员,具备任一门编程基础更易上手。早期入门资料常基于 Xcode 8.2.1(Swift 3.0.2)演示基础语法,但如今 Swift 已演进至 Swift 5.x 与 Swift 6.x(Xcode 16+),基础变量声明与 `print(_:)` 语法仍一脉相承。
第一个 Swift 程序与官方资料入口
Swift 的首个示例通常只需两行顶层代码:`var myString = "Hello, World!"` 使用 `var` 关键字声明可变变量并由字面量自动推断为 `String`,随后调用标准库函数 `print(myString)` 将其输出到控制台并自动换行,无需编写额外的 `main` 函数壳子或行尾分号。本站离线语义脚本解析了上述 `var` 绑定、类型推断与输出行为,并如实探测确认本机未安装 `swift`/`swiftc`。
系统查证语言规范建议优先查阅官方资料(见下表)。尤其在翻阅 Swift Evolution 仓库时,务必区分正式提案与普通草稿:只有带有 `SE-xxxx` 编号的提案才构成版本语言事实依据,其余说明文档不能直接当作规范结论。
Swift 官方权威参考资料
| 资源 | 地址 | 说明 |
|---|---|---|
| The Swift Programming Language | docs.swift.org/swift-book | Apple 官方语言指南(TSPL),系统覆盖全部语法与语义。 |
| Swift.org | www.swift.org | 开源项目官网,提供各平台工具链下载、文档与技术博客。 |
| Swift Evolution | swift.org/swift-evolution | 语言演进提案库,带 SE-xxxx 编号的正式版本规范依据。 |
| Swift 标准库文档 | developer.apple.com/documentation/swift | 标准库核心类型、集合与算法 API 官方参考。 |
离线校验 Swift 首程序语法、SE 提案编号与本机工具链探测
"""Offline Swift 5/6 semantic verification lab for Chapter 01 (tutorial)."""
import json
import re
import shutil
VERSION = "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)"
def case_toolchain_absence_probe():
swift_bin = shutil.which("swift")
swiftc_bin = shutil.which("swiftc")
expected = {"swift_found": False, "swiftc_found": False, "offline_mode": True}
actual = {
"swift_found": swift_bin is not None,
"swiftc_found": swiftc_bin is not None,
"offline_mode": swift_bin is None and swiftc_bin is None,
}
return {
"name": "toolchain_absence_probe",
"summary": "如实探测本机 swift 与 swiftc 可执行文件,确认当前处于离线语义验证环境",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_hello_world_source_and_print():
src = '/* 我的第一个 Swift 程序 */\nvar myString = "Hello, World!"\nprint(myString)\n'
decl = re.search(r'\bvar\s+(\w+)\s*=\s*"([^"]*)"', src)
call = re.search(r"\bprint\(\s*(\w+)\s*\)", src)
sym_table = {}
if decl:
sym_table[decl.group(1)] = {"kind": "var", "type": "String", "value": decl.group(2)}
output = (sym_table[call.group(1)]["value"] + "\n") if (call and call.group(1) in sym_table) else ""
expected = {
"variable": "myString",
"inferred_type": "String",
"mutable_binding": True,
"stdout": "Hello, World!\n",
}
actual = {
"variable": decl.group(1) if decl else "",
"inferred_type": sym_table.get("myString", {}).get("type", ""),
"mutable_binding": sym_table.get("myString", {}).get("kind") == "var",
"stdout": output,
}
return {
"name": "hello_world_source_and_print",
"summary": "解析首程序中的 var 声明、String 类型推断以及 print(_:) 标准输出语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_swift_evolution_proposal_id_rule():
candidates = ["SE-0046", "SE-0296", "SE-0345", "README.md", "docs/pitch-draft"]
se_pattern = re.compile(r"^SE-\d{4}$")
formal = [c for c in candidates if se_pattern.match(c)]
expected = {"formal_proposals": ["SE-0046", "SE-0296", "SE-0345"], "formal_count": 3}
actual = {"formal_proposals": formal, "formal_count": len(formal)}
return {
"name": "swift_evolution_proposal_id_rule",
"summary": "校验正式 Swift Evolution 提案编号 SE-xxxx 规则,区分权威提案与普通仓库文档",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_official_reference_catalog():
refs = [
("The Swift Programming Language", "https://docs.swift.org/swift-book/"),
("Swift.org", "https://www.swift.org/"),
("Swift Evolution", "https://www.swift.org/swift-evolution/"),
("Swift 标准库文档", "https://developer.apple.com/documentation/swift"),
]
expected = {"count": 4, "all_https": True, "domains": ["docs.swift.org", "www.swift.org", "www.swift.org", "developer.apple.com"]}
actual = {
"count": len(refs),
"all_https": all(u.startswith("https://") for _, u in refs),
"domains": [u.split("/")[2] for _, u in refs],
}
return {
"name": "official_reference_catalog",
"summary": "核对 Swift 官方语言指南、官网、提案库与标准库文档四项权威入口",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_toolchain_absence_probe(),
case_hello_world_source_and_print(),
case_swift_evolution_proposal_id_rule(),
case_official_reference_catalog(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 在 CPython 3.12.14 离线脚本中确认 swift/swiftc 缺席状态、Hello World 变量推断与输出、SE-xxxx 规则及 4 项官方入口全部校验通过。
所需环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。
当前源码 SHA256:d3cb3c8b68df01eaf78f45085879c17309f13c9960d0d93c2fca4cdb510a856f
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。
ZIP SHA256:2eb2588d3e2d94ffefb2aa94209b3b3d929695fe8d74bcaaba73c48dd6479ef5
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在阅读 Swift Evolution 资料时,如何快速判断一篇文档是否属于正式语言提案?
展开参考解答
只有带有正式 `SE-xxxx` 编号并经过评审流程的提案文档才是版本事实依据,仓库中无编号的讨论稿或说明文件不能直接当作语言规范。