Encapsulation is one of the fundamental concepts of object-oriented programming. The idea behind Encapsulation is to combine data and functions into a single unit and protect the internal state and functionality from outside manipulations. In order to establish regulated communication between different units, each unit should provide a clear public interface. Swift achieves this behaviour with Access Control.

A very important, but also challenging part of software design is to maintain a high level of Encapsulation when software grows in complexity. Swift provides default access levels for typical scenarios, therefore you don’t need to think too much about it when writing a single-target application. However, when you leave the single-target sector for API design, for example, good Encapsulation can become a very important factor to determine the quality of the API. A very easy example of Encapsulation can be seen in the example below.

class Account {
    private var accountBalance = 0.0

    public func withdraw(amount: Double) throws -> Money { // [1]
        guard accountBalance >= amount else {
            throw TransactionError.insufficientBalance

        accountBalance = accountBalance - amount

        return Money(amount)

    public func deposit(money: Money) -> Bool {
        let amount = money.getAmount()
        accountBalance = accountBalance + amount

        return true

    public func determinBalance() -> Double {
        return accountBalance

The example shows a bank account and the variable accountBalance is declared with the access level private - this means, only the class Account can change the accountBalance. This mechanism is called information hiding. If the accountBalance wasn’t private, any other entity would be able to modify it. So choose your access levels wisely.



Written on May 12, 2019