Menu
Coddy logo textTech

Recap - Bank Account

Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 21 of 57.

challenge icon

Challenge

Medium

Complete the class BankAccount. Its failable initializer init?(owner:deposit:) refuses an empty owner or a negative opening deposit. balance and transactions are private(set). deposit(_:) and withdraw(_:) throw AccountError.invalidAmount for amounts below 1 and withdraw throws AccountError.insufficient(balance:) when the amount is larger than the balance; every successful change is recorded in transactions as +50 or -20. statement() returns Ada: 30 (+50, -20), or Ada: 0 (no transactions).

The supplied code reads the owner and opening deposit (name,amount), then commands d n or w n. It prints cannot open account when the initializer fails; otherwise it prints invalid amount or insufficient funds (balance 10) for failed commands and finally the statement.

Your code goes in AccountError.swift and BankAccount.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

// Supplied input/output code: keep it as it is
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")
}

All lessons in Object Oriented Programming

Practice on your own: Swift playground