Menu
CoddyTech

包裹登记

Coddy 面向 C# 开发者的 Swift 课程的第 43 课,共 48 课。

challenge icon

挑战

中等

完成 add(_ parcel: Parcel) -> Bool 和 count。只添加之前未出现过的 ID;重复的 ID 返回 false,并保留原来的重量。count 是已存储的不同 ID 数量。四个阶段使用相同的文件和驱动程序。Parcel(id:weight:) 是值类型,ParcelDesk() 是引用类型。输入以阶段编号 1 开头,后面跟着 0 到 30 对 ID/重量。ID 由 1 到 10 个小写 ASCII 字母组成,重量为 0 到 100。忽略重复的 ID。输出不同包裹的数量。在对应阶段之前,后续阶段的方法都保留为占位实现。

实现所需的 API 和 solve(_ input: String) -> String。返回不带末尾换行符的输出文本;不要在可编辑代码中打印内容。锁定的驱动程序会使用其他有效输入独立检查这些 API,然后将返回的文本连同且仅连同一个换行符打印出来。所有数值运算都在 Int 的范围内。

你的代码应写在 Parcel.swift、PricePolicy.swift、UnitPrice.swift、ParcelDesk.swift、Functions.swift 中。main.swift 包含提供的输入/输出代码,不能编辑。

亲手试试

import Foundation
func apiChecks(_ input: String) -> Bool {
struct ProbePrice: PricePolicy { func cost(weight: Int) -> Int { weight + 11 } }
let p = input.split(whereSeparator: { $0.isWhitespace }); let stage = Int(p[0])!
let d = ParcelDesk()
guard d.add(Parcel(id: "p", weight: 7)), !d.add(Parcel(id: "p", weight: 9)), d.add(Parcel(id: "q", weight: 2)), d.count == 2 else { return false }
if stage >= 2 { guard d.totalWeight == 9 else { return false } }
if stage >= 3 { guard d.dispatch("missing") == nil && d.count == 2 else { return false }; guard d.dispatch("p")?.weight == 7 && d.count == 1 && d.totalWeight == 2 && d.dispatch("p") == nil else { return false } }
if stage >= 4 { guard UnitPrice(rate: 5).cost(weight: 4) == 20 && d.quote(using: ProbePrice()) == 13 && d.quote(using: UnitPrice(rate: 4)) == 8 else { return false } }
return true
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 开始公开 API 检测
let apiOK = apiChecks(input)
// 结束公开 API 检测
if apiOK { print(solve(input)) } else { print("API mismatch") }

面向 C# 开发者的 Swift中的所有课

自己练习: Swift 在线编辑器