ספר חשבונות בנק
חלק מהיחידה תכנות מונחה עצמים במסלול ה-Swift של Coddy. שיעור 57 מתוך 57.
אתגר
קשהבנו בנק קטן. Account היא מחלקה עם id, owner ו־private(set) var balance, ועם המתודות deposit(_:) ו־withdraw(_:) שזורקות BankError.invalidAmount (מתחת ל־1) ו־BankError.insufficient(id:). Checking מאפשרת משיכת יתר של 100 (היתרה יכולה לרדת עד -100); Savings מסרבת למשיכות שיהפכו את היתרה לשלילית, מוסיפה ריבית של 1% (בעיגול כלפי מטה) ב־monthEnd(), ומאפשרת לכל היותר 2 משיכות בחודש (BankError.limit(id:)), כאשר המונה מתאפס באמצעות monthEnd(). Account.monthEnd() לא עושה דבר. המחלקה Bank מאחסנת חשבונות לפי מזהה ויש לה את transfer(from:to:amount:), שמבצעת משיכה והפקדה או לא מבצעת דבר במקרה של כישלון.
הקוד שסופק קורא פקודות open checking 1 ada, open savings 2 bo, dep 1 100, wd 2 30, tr 1 2 50 או month, מדפיס ok או את השגיאה (invalid amount, insufficient funds in 2, withdrawal limit on 2, no account 9), ולבסוף מדפיס כל חשבון כשהחשבונות ממוינים לפי מזהה, בפורמט 1 ada checking: -20.
הקוד שלך יופיע בקבצים BankError.swift, Account.swift, Checking.swift, Savings.swift ו־Bank.swift. הקובץ main.swift מכיל את קוד הקלט/פלט שסופק ואי אפשר לערוך אותו.
נסו בעצמכם
// קוד הקלט/פלט שסופק: יש להשאיר אותו כפי שהוא
var input: [String] = []
while let line = readLine() { input.append(line) }
let bank = Bank()
for cmd in input {
let p = cmd.split(separator: " ").map(String.init)
do {
switch p[0] {
case "open":
let id = Int(p[2])!
bank.accounts[id] = p[1] == "savings" ? Savings(id: id, owner: p[3]) : Checking(id: id, owner: p[3])
case "dep": try bank.account(Int(p[1])!).deposit(Int(p[2])!)
case "wd": try bank.account(Int(p[1])!).withdraw(Int(p[2])!)
case "tr": try bank.transfer(from: Int(p[1])!, to: Int(p[2])!, amount: Int(p[3])!)
default: bank.accounts.values.forEach { $0.monthEnd() }
}
print("ok")
} catch BankError.invalidAmount {
print("invalid amount")
} catch BankError.insufficient(let id) {
print("insufficient funds in \(id)")
} catch BankError.limit(let id) {
print("withdrawal limit on \(id)")
} catch BankError.noAccount(let id) {
print("no account \(id)")
} catch {
print("error")
}
}
for id in bank.accounts.keys.sorted() {
let a = bank.accounts[id]!
print("\(a.id) \(a.owner) \(a.kind): \(a.balance)")
}
כל השיעורים ביחידה תכנות מונחה עצמים
תרגלו בעצמכם: Swift אונליין