Using private(set) and why it’s important

Why even use private(set) when you can just declare the variable

struct BankAccount {

var owner:String
var balance:Double


}

Imagine you’re creating an app for a bank and every owner has a balance. Naturally, you may define a struct above with the variable balance and move on.

Now the balance can be changed from anywhere in your app.

When you create an instance of BankAccount you can set the balance and then change it anywhere in code without using private(set).

var myAccount = BankAccount(owner: "Jim", balance: 800)

This creates an owner named Jim with an initial balance of 800. Now he has money in his bank account.

Now I can change this

myAccount.balance = 20000

Does Jim have 20,800 in his balance or 20,000?

Jim has 20,000, the balance of 800 was overwritten in code outside of the struct. This can happen accidentally in code if your not using private(set).

In order to prevent this from happening let’s use private(set).

struct BankAccount {

var owner:String
private(set) var balance:Double


}

Type private(set) in front of var balance: Double

Now if you try to change myAccount.balance = 20000, you will get an error. Cannot assign to property: ‘balance’ setter is inaccesible.

You can only change or set the balance from within your struct using a mutating function.

If you type func depositIntoAccount(amount: Double) and try to change balance, you’ll get an error, Left side of mutating operator isn’t mutable: ‘self’ is immutable.

struct BankAccount {

var owner:String
private(set) var balance:Double

func depositIntoAccount(amount: Double){

 balance += amount


}


}

Instead you need to use mutating in front of function.

struct BankAccount {

var owner:String
private(set) var balance:Double

mutating func depositIntoAccount(amount: Double){

 balance += amount


}


}

Now, you can always get or display myAccount.balance but won’t be able to change the balance from outside of the struct unless your creating an instance for the first time.

Remember to always use private(set) in your code when it’s necessary.

Check out my blog post Swift Guard vs If: Why the “Bouncer” Beats the “Pyramid” to learn how to use guard to set prevent our function from creating a negative balance.

Master Swift, One Tip a Day

Join other developers getting one bite-sized Swift lesson delivered to their inbox every morning.

🚀 Awesome! Check your inbox for your first tip.
Something went wrong. Try again.

1 thought on “Using private(set) and why it’s important”

  1. Pingback: Swift Guard vs If: Why the “Bouncer” Beats the “Pyramid” – Swift Owls

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top