Problem overview
The lesson asks for a BankAccount class that keeps its balance hidden. Code outside the class can't read or write the balance directly. It can only call methods, and those methods enforce the rules. This is encapsulation: the object protects its own data.
The class needs an initializer init(_ initialBalance: Double) and three methods:
deposit(_ amount: Double)adds to the balance and silently ignores amounts of zero or less.withdraw(_ amount: Double) -> Boolrefuses amounts that are zero, negative or larger than the balance, and returnsfalsewithout changing anything. Otherwise it subtracts the amount and returnstrue. Taking out exactly the whole balance is allowed.getBalance() -> Doubleis the only way to read the balance from outside.
The driver starts with 100, deposits 50, withdraws 30 (leaving 120) and attempts to withdraw 200, which is refused. Then it tries a deposit of -20, a deposit of 0 and a withdrawal of -5, all of which are ignored. Withdrawing 120 succeeds and empties the account, and withdrawing 1 more is refused. The output is:
Balance: 120
Balance: 120
Withdrew all
Balance: 0
Rejected
Approach: guard first, change second
Both deposit and withdraw follow the same shape. Check whether the request is valid, leave early if it isn't, and only then touch the balance. Doing the check first means a bad request can never leave the account half-changed.
The balance is declared private var balance: Double. Private means only code inside BankAccount can use it. Anyone else who writes account.balance gets a compile error: 'balance' is inaccessible due to 'private' protection level. That is the point of the lesson. The rules in deposit and withdraw can't be bypassed, because there is no other route to the number.
Step by step
- Declare the class and write its closing brace at once, so everything that follows has a home.
- Add the private property
balanceof typeDouble. It usesvarbecause deposits and withdrawals change it. - Write the initializer. Its parameter is
_ initialBalance; the underscore lets callers writeBankAccount(100)with no argument label. - Store the starting value in
balance. A new account starts with whatever it is given. - Start
deposit. It returns nothing, because a deposit changes state and has no answer to give. - Reject non-positive amounts with a one-line
if amount <= 0 { return }. - Add the amount to the balance. Only positive amounts get this far.
- Start
withdraw, returning aBoolso the caller learns whether the money left. - Refuse bad requests with
if amount <= 0 || amount > balance { return false }. The comparison is>, not>=, which is why withdrawing the whole balance works. - Subtract the amount from the balance.
- Return
true. Reaching this line means the withdrawal happened. - Add
getBalance, which returns aDouble, and returnbalancefrom it. A getter lets outside code read the value without being able to change it.
The solution in Swift
class BankAccount {
private var balance: Double
init(_ initialBalance: Double) {
balance = initialBalance
}
func deposit(_ amount: Double) {
if amount <= 0 { return }
balance += amount
}
func withdraw(_ amount: Double) -> Bool {
if amount <= 0 || amount > balance { return false }
balance -= amount
return true
}
func getBalance() -> Double {
return balance
}
}
class Solution {
func mainFunction() {
let account = BankAccount(100)
account.deposit(50)
account.withdraw(30)
account.withdraw(200)
print("Balance: \(Int(account.getBalance()))")
account.deposit(-20)
account.deposit(0)
account.withdraw(-5)
print("Balance: \(Int(account.getBalance()))")
if account.withdraw(120) {
print("Withdrew all")
}
print("Balance: \(Int(account.getBalance()))")
if !account.withdraw(1) {
print("Rejected")
}
}
}
Details worth knowing
- The balance is a
Double, so Swift prints it as120.0. The driver wraps it inInt(...)to print120.Int(_:)on aDoubledrops the fractional part rather than rounding. - Ignoring the result of
withdraw. The driver callsaccount.withdraw(30)as a statement. Because the method returns aBooland isn't marked@discardableResult, the compiler warnsresult of call to 'withdraw' is unused. It is only a warning, and the program runs. - Early
returnin a method with no return type. Indeposit, a barereturnsimply leaves the method. - Classes are reference types, so a
let account = BankAccount(100)can still change its balance through methods.letonly stops you from pointing the name at another account.
Edge cases and common mistakes
- Using
>=in the withdraw guard. That would refuse a withdrawal of exactly the balance, and the driver'sWithdrew allline would never print. - Forgetting the
amount <= 0check inwithdraw. A negative withdrawal would increase the balance, which is a deposit that skips the deposit rules. - Zero amounts. Zero is not positive, so both methods must ignore it. A deposit of 0 leaves the balance alone, and a withdrawal of 0 returns
false. - Changing the balance before checking. Subtracting first and validating afterwards leaves the account wrong when the request is refused.
- Making
balancenon-private. The tests may still pass, but outside code could then set it to anything and the lesson's protection would be gone. - Floating-point rounding. Because the balance is a
Double, repeated fractional amounts add up inexactly. Starting at 0 and depositing 0.1 ten times gives a balance of 0.9999999999999999, so a withdrawal of 1.0 is refused. The lesson's driver uses whole numbers, so it never meets this.
Testing
Each call below uses the solution above, and the output shows the result of withdraw followed by the balance:
let account = BankAccount(100)
account.deposit(50)
print(account.withdraw(30), account.getBalance())
print(account.withdraw(200), account.getBalance())
print(account.withdraw(-5), account.getBalance())
print(account.withdraw(120), account.getBalance())
print(account.withdraw(1))
true 120.0
false 120.0
false 120.0
true 0.0
false
Try these in the editor above, along with a deposit of a negative amount between the calls to confirm that the balance doesn't move.
