Hidden feature: private properties


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


I’m sure you’re already familiar with private properties.

They are very useful when we want to make a property inaccessible outside of the type where it was defined.

However, there are situations where we would like to allow a property to be read from the outside, but still prevent it from being updated from the outside.

The first solution that comes to mind would be to introduce a new public computed property, that would, under the hood, return the value of an underlying private property.

However this solution is far from great!

First, because we would need to declare a new separate property each time.

And also because the naming between the public and the private properties will become confusing really fast.

But that’s when a hidden feature of private properties comes into play!

As it turns out, it’s actually possible to declare different protection levels for the getter and the setter of a property.

To implement this, we can start by using the keyword public to declare the protection level of the getter.

And then we can use the keyword private(set) to declare a second protection level, that will only apply to the setter.

Now if we run the code, we can see that the getter is indeed accessible from outside whereas the setter is not 👌

That’s all for this article, I hope you’ve enjoyed learning this new trick!

Here’s the code if you want to experiment with it:

import Foundation

struct Person {
    public private(set) var name: String

    init(name: String) {
        self.name = name
    }
}

let person = Person(name: "Vincent")

person.name // ✅ This code is still valid

person.name = "New Name" // ❌ Cannot assign to property: setter is inaccessible
Previous
Previous

Here are 3 Swift Macros you can start using today 🤌

Next
Next

Did you know you can use Copilot with an Xcode project? 🤖