Menu
CoddyTech

复习:银行账户

本课属于 Coddy Swift 学习旅程的“面向对象编程”单元。第 21 课,共 57 课。

challenge icon

挑战

中等

完成 BankAccount 类。它的可失败初始化器 init?(owner:deposit:) 会拒绝空的所有者名称或负数的初始存款。balance 和 transactions 是 private(set)。当金额小于 1 时,deposit(_:) 和 withdraw(_:) 会抛出 AccountError.invalidAmount;当取款金额大于余额时,withdraw 会抛出 AccountError.insufficient(balance:);每次成功的余额变动都会以 +50 或 -20 的形式记录在 transactions 中。statement() 会返回 Ada: 30 (+50, -20),或 Ada: 0 (no transactions)。

提供的代码会读取所有者名称和初始存款(name,amount),然后读取 d n 或 w n 命令。初始化器失败时会输出 cannot open account;否则,对于执行失败的命令,会输出 invalid amount 或 insufficient funds (balance 10),最后输出账户明细。

你的代码应写在 AccountError.swift 和 BankAccount.swift 中。main.swift 包含提供的输入/输出代码,不能编辑。

亲手试试

// 提供的输入/输出代码:保持原样。
var input: [String] = []
while let line = readLine() { input.append(line) }
let head = input[0].split(separator: ",", omittingEmptySubsequences: false).map(String.init)
if let account = BankAccount(owner: head[0], deposit: Int(head[1])!) {
    for cmd in input.dropFirst() {
        let p = cmd.split(separator: " ")
        let n = Int(p[1])!
        do {
            if p[0] == "d" { try account.deposit(n) } else { try account.withdraw(n) }
        } catch AccountError.insufficient(let balance) {
            print("insufficient funds (balance \(balance))")
        } catch {
            print("invalid amount")
        }
    }
    print(account.statement())
} else {
    print("cannot open account")
}

面向对象编程中的所有课

自己练习: Swift 在线编辑器