user1007047
user1007047

Reputation: 48

Swift protocol extensions and immutable properties

I'm new to Swift and playing with protocol extensions. In the following code I can't seem to protect the struct property holdings from direct manipulations.

enum BankingError: Error {
    case insufficientFunds
}

protocol Banking {
    var holdings: Int { get set }
    mutating func deposit(_ amount: Int)
    mutating func withdraw(_ amount: Int) throws
}

extension Banking {    
    mutating func deposit(_ amount: Int) {
        holdings += amount
    }
    
    mutating func withdraw(_ amount: Int) throws {
        guard amount <= holdings else { throw BankingError.insufficientFunds }
        holdings -= amount
    }
}

struct Bank: Banking {
    var holdings: Int
}

// Usage
var bank = Bank(holdings: 0)
bank.deposit(1)
try bank.withdraw(1)
do {
    try bank.withdraw(1)
} catch BankingError.insufficientFunds {
    print("Computer says 'No'")
}
// Disallow direct mutation of holdings?
bank.holdings = 0
bank.holdings += 1
bank.holdings -= 2
// Getter is OK
print(bank.holdings)

If the methods were implemented as part of the struct I could have declared holdingsas private(set), is there an equivalent option in this case?

Upvotes: 0

Views: 68

Answers (0)

Related Questions