C++ 与 Swift 对照
同一个程序分别用 C++ 和 Swift 编写,取自本课程的课时。
绑定与可变性
C++ 的 auto 用于请求类型推断,本身不会让局部变量不可变;const 则提供单独的限制。Swift 也会推断固定类型,但会明确区分 let 和 var。C++ 的 const 对象可以在运行时初始化,而 constexpr 还会施加额外的常量表达式规则。Swift 的 let 也允许在运行时初始化。示例会重新赋值字符串,然后保留一个标签。C++ 中指针的 const 性与被指向对象的 const 性是不同的,而且 const 智能指针仍可能暴露可变的被指向对象状态。类似地,Swift 的 let…
C++1#include <iostream>2#include <string>3#include <vector>4#include <map>5#include <set>6#include <optional>7#include <memory>8#include <tuple>9#include <variant>10#include <stdexcept>11#include <algorithm>12 13int main() {14auto mode = std::string("draft");15 mode = "ready";16 const auto label = mode;17 std::cout << label << '\n';18}Swift1var mode = "draft"2mode = "ready"3let label = mode4print(label)字符串与插值
C++ 可以通过流、拼接或格式化库构建格式化文本,而 Swift 则使用反斜杠和圆括号在 String 内部直接插值表达式。std::string 具有值语义和可变字符存储;复制它通常不会创建指向同一个可变字符串对象的第二个引用。Swift String 也具有值语义,但它提供基于 Character 的遍历,而不是用整数索引字节。所示的算术运算较小,在两种语言中都可以表示。生成格式化文本与解析或验证数字输入是分开的,格式化示例并不确立 Unicode 索引行为。
C++1#include <iostream>2#include <string>3#include <vector>4#include <map>5#include <set>6#include <optional>7#include <memory>8#include <tuple>9#include <variant>10#include <stdexcept>11#include <algorithm>12 13int main() {14int side = 4;15 std::cout << side << " squared = " << side * side << '\n';16}Swift1let side = 42print("\(side) squared = \(side * side)")Switch 与模式
C++ 中的 switch 接收整型或枚举条件,并且在控制流未显式退出时允许在 case 主体之间贯穿(fallthrough)。Swift 中的 switch 则支持字符串和更丰富的模式匹配,并在每个 case 结束时自动退出。它的匹配必须覆盖所有可能的输入,或者包含一个 default 分支。源语言代码比较的是单字节命令字符;目标语言代码则接受完整的字符串命令。C++ 中相邻的 case 标签可以共享一个主体,而 Swift 则是在单个 case 中对多个模式进行分组。Swift 中显式的…
C++1#include <iostream>2#include <string>3#include <vector>4#include <map>5#include <set>6#include <optional>7#include <memory>8#include <tuple>9#include <variant>10#include <stdexcept>11#include <algorithm>12 13int main() {14char command = 'w';15 switch (command) {16 case 'w': case 's': std::cout << "write\n"; break;17 default: std::cout << "ignore\n"; break;18 }19}Swift1let command = "w"2switch command {3case "w", "save": print("write")4default: print("ignore")5}函数与标签
C++ 和 Swift 都支持独立函数和默认参数,但普通的 C++ 调用不会使用 Swift 的外部参数标签。Swift 将调用处的标签与函数内部的参数名区分开来;下划线会隐藏该外部标签。在 Swift 函数中,参数是常量绑定,除非显式的局部副本或 inout 契约改变了这种设计。示例返回用分隔符连接的文本,打印仍由调用方负责。当存在像 times 这样必需的标签时,仅靠匹配的参数顺序无法实现完整的 Swift 可调用接口。
C++1#include <iostream>2#include <string>3#include <vector>4#include <map>5#include <set>6#include <optional>7#include <memory>8#include <tuple>9#include <variant>10#include <stdexcept>11#include <algorithm>12std::string repeat_text(const std::string &text, int times) {13 std::string result;14 for (int i = 0; i < times; ++i) { if (i) result += "/"; result += text; }15 return result;16}17 18int main() {19std::cout << repeat_text("ha", 3) << '\n';20}Swift1func repeatText(_ text: String, times: Int) -> String {2 return Array(repeating: text, count: times).joined(separator: "/")3}字典与缺失的键
C++ 的 std::map::operator[] 会为缺失的键插入默认值,而 find 可以在不插入的情况下检查键是否存在,at 则会在缺失条目时抛出异常。Swift Dictionary 的普通查找会返回一个 Optional,通过下标赋值 nil 则会移除该映射。请根据读取操作是否会改变状态来选择合适的查找 API。示例中移除了 zoom,并使用 100 作为回退值。std::map 会按顺序遍历键,而 std::unordered_map 和 Swift Dictionary…
C++1#include <iostream>2#include <string>3#include <vector>4#include <map>5#include <set>6#include <optional>7#include <memory>8#include <tuple>9#include <variant>10#include <stdexcept>11#include <algorithm>12 13int main() {14std::map<std::string, int> settings{{"zoom", 125}};15 settings.erase("zoom");16 auto found = settings.find("zoom");17 std::cout << (found == settings.end() ? 100 : found->second) << '\n';18}Swift1var settings = ["zoom": 125]2settings["zoom"] = nil3print(settings["zoom"] ?? 100)结构体与独立副本
C++ 的默认逐成员复制和 Swift 结构体赋值会保留各个字段的语义。std::string 成员会复制其值,而 shared_ptr 成员会继续与原对象共享所有权。在这个示例中,Swift 的 String 值和类引用字段也有类似的区别。更改复制品的标签不会影响原始标签,但更改共享单元格后,两个副本都能看到变化。C++ 支持自定义复制操作,因此这并不是适用于所有类的通用规则。Swift 中会修改结构体的方法需要使用 mutating;修改被引用的类实例不会替换结构体中包含的字段。
C++1#include <iostream>2#include <string>3#include <vector>4#include <map>5#include <set>6#include <optional>7#include <memory>8#include <tuple>9#include <variant>10#include <stdexcept>11#include <algorithm>12struct Cell { std::string text; };13struct LabelledBox { std::string label; std::shared_ptr<Cell> shared; };14 15int main() {16LabelledBox original{"old", std::make_shared<Cell>(Cell{"one"})};17 auto copy = original;18 copy.label = "new";19 copy.shared->text = "two";20 std::cout << original.label << ' ' << original.shared->text << '\n';21}Swift1final class Cell { var text: String; init(text: String) { self.text = text } }
课程大纲
10 章48 节课1 个项目48 个挑战99 道测验题常见问题
面向 C++ 开发者的 Swift 课程 适合谁学习?
适合已经会写 C++、想学 Swift 的人。每节课都从你熟悉的 C++ 代码出发,展示 Swift 如何实现同样的事情,所以你可以跳过入门基础。
需要先会 Swift 吗?
不需要。课程从你的第一个 Swift 程序开始。你需要掌握 C++ 基础:变量、条件、循环、函数和集合。
面向 C++ 开发者的 Swift 课程 有多少节课?
面向 C++ 开发者的 Swift 课程 包含 48 节互动课,你可以按自己的节奏完成。
面向 C++ 开发者的 Swift 课程 包含哪些内容?
本课程分为以下几章:Swift 入门, 文本与决策, 控制流, 函数与数组, and more。
面向 C++ 开发者的 Swift 课程 免费吗?
是的。Coddy 上的每门课程都可以免费开始。你可以直接在浏览器中完成课程,无需下载,也无需注册。