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 20,000+ Swift developers and enthusiasts who get my weekly updates.