回顾:支付系统
本课属于 Coddy Swift 学习旅程的“面向对象编程”单元。第 31 课,共 57 课。
挑战
困难使用协议设计一个支付系统。PaymentMethod 要求包含 name、fee(for amount: Int) -> Int 和 mutating func pay(_ amount: Int) -> Bool。协议扩展提供 total(for:)(金额加手续费)。实现 Card(手续费为 2%,向下取整,始终支付成功,并统计 payments)、Wallet(包含存储的 balance,不收手续费,总金额超过余额时支付失败,否则扣除相应金额)和 GiftCard(包含存储的 balance,不收手续费,尽可能支付:余额不足时拒绝支付)。完成 checkout(_:with:),按给定顺序尝试每种支付方式,返回第一个支付成功的方式对应的 paid 100 with wallet (fee 0);如果都不成功,则返回 declined。它还会返回更新后的支付方式,以便在后续购买中保留余额变化。
提供的代码会读取钱包余额和礼品卡余额,然后读取购买金额。每笔购买都会按礼品卡、钱包、银行卡的顺序尝试支付,并打印结果,最后打印余额。
你的代码要写在 PaymentMethod.swift、Card.swift、Wallet.swift、GiftCard.swift 和 Functions.swift 中。main.swift 包含提供的输入输出代码,不能编辑。
亲手试试
// 已提供的输入/输出代码:保持原样。
var input: [String] = []
while let line = readLine() { input.append(line) }
var methods: [any PaymentMethod] = [GiftCard(balance: Int(input[1])!), Wallet(balance: Int(input[0])!), Card()]
for line in input.dropFirst(2) {
let (result, updated) = checkout(Int(line)!, with: methods)
methods = updated
print(result)
}
for m in methods {
if let g = m as? GiftCard { print("gift card left \(g.balance)") }
if let w = m as? Wallet { print("wallet left \(w.balance)") }
if let c = m as? Card { print("card payments \(c.payments)") }
}
面向对象编程中的所有课
自己练习: Swift 在线编辑器