从 Swift 到 Ruby
录制器:多语言 Swift 适配器(swiftc + 生成的驱动程序)。自由函数和静态方法可以录制。Vapor 路由通过 app record/replay 进行检查。
语言结构
throws:throw ValidationError.empty->raise ValidationError, "empty",每个错误枚举对应一个 Ruby 类;普通的无效输入则用ArgumentError。- Optional:
String?->nil;if let/guard let->return ... if x.nil?;??->.nil? ? d : x;强制解包!-> 只有在录制的用例体现时才 raise。 - 结构体/枚举:值类型 ->
Data.define;带关联值的枚举 -> 每个 case 一个Data.define+case ... in;Codable的键决定 JSON 字段名(CodingKeys)。 - 集合:
map/filter/reduce/compactMap/first(where:)/sorted(by:)->map/select/reduce/filter_map/find/sort_by。 - Vapor:
app.get("x", ":id") { req in ... }-> 路由 + action;req.parameters.get("id")->params[:id];Abort(.notFound)-> 返回录制响应体的head :not_found。
陷阱
- 整数溢出会触发 trap(崩溃),而不是回绕;
&+才会回绕。/向零截断(Ruby 向下取整);%的结果符号与被除数相同(remainder)。 - 舍入:
rounded()把 .5 远离零舍入(Ruby 的round);.toNearestOrEven->round(half: :even)。String(format: "%.2f")->format("%.2f")。 - 字符串:
count统计字素簇(带肤色的 emoji 算 1);Ruby 的length统计码点:使用s.grapheme_clusters.length。索引使用String.Index,而不是整数。 - Dictionary 的顺序是随机的:如果输出来自 Dictionary 就要排序。