Last active
November 29, 2021 13:56
-
-
Save yimajo/1e3d661ce9e5acc4140c42a09677f32a to your computer and use it in GitHub Desktop.
クリーンアーキテクチャ本のLoanというEntityをSwiftで表現してみる
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Loan { | |
// 借入元金 | |
private var principle: Double | |
// 貸出金利 もしくは 貸出利率 の 百分率。0%や100% | |
private var rate: Double | |
// 貸し出し期間 | |
var period: TimeInterval | |
// 借金総額 | |
private var balance: Double { | |
didSet { | |
print("借金総額:", balance) | |
} | |
} | |
init(principle: Double, rate: Double, period: Double) { | |
self.principle = principle | |
self.rate = rate | |
self.period = period | |
self.balance = principle | |
} | |
// Make a payment against the loan. | |
// ローンに対して支払いを行う。 | |
func makePayment(paymentAmount: Double) { | |
let newCalculatedBalance = balance - paymentAmount | |
guard newCalculatedBalance >= 0 else { | |
// ローン残高が0より低くなっている | |
assertionFailure("今は考えない") | |
return | |
} | |
balance = newCalculatedBalance | |
} | |
// Apply the interest for the elapsed period. | |
// The total accrued interest value. | |
// 経過した期間の利息を適用します。 | |
// 経過した利息の合計値を返す。 | |
func applyInterest() { | |
// ローン残高が増えてしまう | |
balance = principle * (1 + (rate / 100)) | |
} | |
// 遅延損害金 | |
func chargeLateFee() { | |
let rateFee = 999.0 | |
balance += rateFee | |
} | |
} | |
// $1000を借金し、1秒につき10%の金利とした | |
let loan = Loan(principle: 1000, rate: 10, period: 1) | |
// 1秒過ぎて | |
DispatchQueue.main.asyncAfter(deadline: .now() + loan.period) { | |
// 利息適用され | |
loan.applyInterest() | |
// 頑張って$100かえす | |
loan.makePayment(paymentAmount: 100) | |
// 1秒過ぎて利息適用 | |
DispatchQueue.main.asyncAfter(deadline: .now() + loan.period) { | |
// 利息適用され | |
loan.applyInterest() | |
// 特に期限決めてないけど遅延損害金が加算されてみる | |
loan.chargeLateFee() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
参考
https://jameseastham.co.uk/posts/clean-architecture-in-net-core-56gh