Skip to content

從 Swift 到 Ruby

Recorder:polyglot Swift adapter(swiftc + 產生的 driver)。自由函式與 static 方法可以錄製。Vapor 路由透過 app record/replay 檢查。

語法結構

  • throws:throw ValidationError.empty -> raise ValidationError, "empty",每個錯誤 enum 都對應一個 Ruby 類別;單純的無效輸入則用 ArgumentError。
  • Optional:String? -> nil;if let/guard let -> return ... if x.nil?;?? -> .nil? ? d : x;強制解包 ! -> 只有在錄製案例顯示會出錯的地方才拋出錯誤。
  • Struct/enum:值型別 -> Data.define;帶有關聯值的 enum -> 每個 case 一個 Data.define + case ... in;JSON 名稱由 Codable 的鍵決定(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,並搭配錄製下來的 body。

陷阱

  • 整數溢位會觸發 trap(程式當掉),而不是繞回;&+ 才會繞回。/ 向零截斷(Ruby 是向下取整);% 的正負號跟隨被除數(remainder)。
  • 四捨五入:rounded() 遇到 .5 時遠離零進位(等同 Ruby 的 round);.toNearestOrEven -> round(half: :even)。String(format: "%.2f") -> format("%.2f")。
  • 字串:count 計算的是字素叢集(帶膚色的 emoji 算 1 個);Ruby 的 length 計算的是 code point:請使用 s.grapheme_clusters.length。索引使用 String.Index,而不是整數。
  • Dictionary 的順序是隨機的:如果輸出來自 Dictionary,請先排序。
在 GitHub 上編輯此頁 →