ARTICLE / SWIFT

Using private(set) and why it's important

By Ryan Relf January 21, 2026 swift

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.

SWIFT OWLS RELEASE LIST

Get the next useful build in your inbox.

New components, integrations, courses, and technical notes. No generic newsletter filler.

FROM THE LIBRARY

Need the implementation too?

Browse reusable components, complete flows, integrations, and training built from the same work.

Browse the library →
DISCUSSION

1 comment

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

[…] Lets piggyback off of the previous blog post where I showed you why private(set) was needed to protect your variables. You can read that post here : Using private(set) and why it’s important. […]