Public Getters and Private Setters in Swift

Accessible rather the settable. GO!

Image for post
Image for post
Photo by Markus Spiske on Unsplash

You have a public class or struct, and want the client of the object to be able to access a property but not set it. What to do...

Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 11.5, and Swift 5.2.4

Prerequisites:

The example

Imagine you have a Person class. You don't need a great imagination, because here is a possible Class right here HERE:

Image for post
Image for post
Click for Gist

The thinking behind this is that someone’s age is likely to change (I don’t know about you, but my age changes every year, usually increasing). This means that I’m comfortable with the name being changed, but the age, not so much.

WE SHOULDN’T BE ALLOWED TO CHANGE THE NAME DIRECTLY.

Solution number 1

Use the private modifier for the age, but that means we can’t access the age at all! How can we get over this impass? We can access the property through a function.

Image for post
Image for post
Click for Git

Which is…ok…but this invovles us creating a new function just to access the property.

Solution number 2

Here we go.

Image for post
Image for post
Click for Gist

This makes our class much closer to the initial class. While giving us the functionality that we want.

That’s an awesome!

Conclusion

Everytime we learn more features of a programming language we have more tools in order to solve software problems.

That is what this article is about — helping you to solve issues through implementation in Swift.

I hope this has helped you out!

If you’ve any questions, comments or suggestions please hit me up on Twitter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store