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:
1 2 3 4 5 6 7 8 9 10 11 |
struct Counter { // `count` here has to be a var // but I never want to set the `count` externally, // so I made it private private var count: Int // so this is the only way to access the count externally func getCount() { return count } } |
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:
1 2 3 4 |
struct Counter { // I specify that only the setter is private! private(set) var count: Int } |
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:
1 2 3 4 |
public struct Counter { // I specify that only the setter is private! public private(set) var count: Int } |
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!