Public Getters and Private Setters in Swift
Accessible rather the settable. GO!
You have a public
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
- This article is written in a Playground but I’m assuming you are comfortable with classes and structures (Class and Struct
Imagine you have a
Person class. You don't need a great imagination, because here is a possible
Class right here HERE:
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.
Which is…ok…but this invovles us creating a new function just to access the property.
Solution number 2
Here we go.
This makes our
class much closer to the initial
class. While giving us the functionality that we want.
That’s an awesome!
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