Start learning free

LESSON 66 OF 71 · PROJECTS: OBJECT-ORIENTED

Bank Account in Swift: Encapsulation with a Private Balance

Practice Read the full explanation

Build a BankAccount class that keeps its balance private and lets other code change it only through methods that check the rules. This is encapsulation: the object protects its own data.

Private balance. Declare private var balance: Double, so only the class can touch it.

What the class must have (Swift):

  • The initializer init(_ initialBalance: Double): creates an account that starts with the given balance.
  • func deposit(_ amount: Double): adds amount to the balance. If amount is zero or negative, do nothing (no error, the balance stays the same).
  • func withdraw(_ amount: Double) -> Bool: if amount is zero or negative, or larger than the balance, change nothing and return false. Otherwise subtract it from the balance and return true. Withdrawing exactly the whole balance is allowed (the balance becomes 0).
  • func getBalance() -> Double: returns the current balance. It is the only way for outside code to read it.

Swift's Double prints as 120.0, so the driver uses Int(...) to print 120.

The driver. The driver at the end of the starter code is already written and uses your class. It runs these checks:

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")
        }
    }
}

Walk through it: start with 100, deposit 50 (150), withdraw 30 (120), withdraw 200 is refused (still 120). Then deposit -20, deposit 0 and withdraw -5 are all ignored (still 120). Withdrawing 120 succeeds and empties the account, so the balance is 0, and withdrawing 1 more is refused.

Expected output:

Balance: 120
Balance: 120
Withdrew all
Balance: 0
Rejected

Both deposit and withdraw start with a guard that rejects amount <= 0. Write the guard first, then the change to the balance.

private var balance: Double, then in the initializer balance = initialBalance.

if amount <= 0 || amount > balance { return false }, then balance -= amount and return true.

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")
        }
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    SWIFT · PROJECTS: OBJECT-ORIENTED

    Bank Account in Swift, explained

    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) -> Bool refuses amounts that are zero, negative or larger than the balance, and returns false without changing anything. Otherwise it subtracts the amount and returns true. Taking out exactly the whole balance is allowed.
    • getBalance() -> Double is 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

    1. Declare the class and write its closing brace at once, so everything that follows has a home.
    2. Add the private property balance of type Double. It uses var because deposits and withdrawals change it.
    3. Write the initializer. Its parameter is _ initialBalance; the underscore lets callers write BankAccount(100) with no argument label.
    4. Store the starting value in balance. A new account starts with whatever it is given.
    5. Start deposit. It returns nothing, because a deposit changes state and has no answer to give.
    6. Reject non-positive amounts with a one-line if amount <= 0 { return }.
    7. Add the amount to the balance. Only positive amounts get this far.
    8. Start withdraw, returning a Bool so the caller learns whether the money left.
    9. Refuse bad requests with if amount <= 0 || amount > balance { return false }. The comparison is >, not >=, which is why withdrawing the whole balance works.
    10. Subtract the amount from the balance.
    11. Return true. Reaching this line means the withdrawal happened.
    12. Add getBalance, which returns a Double, and return balance from 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 as 120.0. The driver wraps it in Int(...) to print 120. Int(_:) on a Double drops the fractional part rather than rounding.
    • Ignoring the result of withdraw. The driver calls account.withdraw(30) as a statement. Because the method returns a Bool and isn't marked @discardableResult, the compiler warns result of call to 'withdraw' is unused. It is only a warning, and the program runs.
    • Early return in a method with no return type. In deposit, a bare return simply leaves the method.
    • Classes are reference types, so a let account = BankAccount(100) can still change its balance through methods. let only 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's Withdrew all line would never print.
    • Forgetting the amount <= 0 check in withdraw. 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 balance non-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.

    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free