복습 - 은행 계좌
Coddy Swift 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 21번째.
챌린지
중급BankAccount 클래스를 완성하세요. 실패 가능한 이니셜라이저 init?(owner:deposit:)는 소유자가 비어 있거나 개설 입금액이 음수인 경우를 거부합니다. balance와 transactions는 private(set)입니다. deposit(_:)과 withdraw(_:)는 1 미만의 금액에 대해 AccountError.invalidAmount를 발생시키며, 금액이 잔액보다 클 때 withdraw는 AccountError.insufficient(balance:)를 발생시킵니다. 성공한 모든 변경 사항은 transactions에 +50 또는 -20으로 기록됩니다. 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 플레이그라운드