Swift Magic: Public Getter, Private Setter

In my blog post on Constructor Injection, I had an example of a struct with a property that needed to be read externally but written only internally. I initially wrote the code like this:

I was not happy with this, but that’s the only way I could think of for making it do what I needed to do. Luckily, there is a better way!

@mipstian pointed out that I can choose to make only the setter private in Swift! Like this:

In my case, I’m ok with Counter being “public” to my module (aka internal). However, if you are building an SDK, you can make it make the getter public while keeping the setter private like this:

Not sure how I missed it (I think that’s because I tend to use let as much as possible 😇), but I’m glad to find this amazingly elegant feature of Swift I didn’t even know about!

Enjoy the article? Join over 14,500+ Swift developers and enthusiasts who get my weekly updates.

  • Awesome!

  • Bionik6

    Neat, really neat. That’s why I love the Swift language. I was exactly using the syntax of your first example but now I’ll use the private(set) syntax for upcoming projects.
    Thank you for sharing Natasha 🙂

  • Joshua Kaden

    How funny; I just discovered the same feature last night!

  • Vince O’Sullivan

    This simple construct is very welcome news. I had previously used a public and a private variable to achieve this but having it built into the language is much more succinct.

    • Nuno

      Dido 🙂

  • Drew Cover

    Yeah. It is nice that it is available.

    I find it a little irritating private(set) is allowed but not public(get) which is more readable to me. “public let” and “private(set) var” are functionally equivalent (ignoring module/package differences) and often sit together in my code. It is annoying that they look opposite. (Yes, I understand why it is this way, cuz Module Accessibility is default-I think file accessibility/private should be default, and modifiers should be required to make it more public. )

  • Jason Thompson

    C# has had this feature for a long time.. it’s a real time saver! Thanks for sharing the swift equivalent.