Oftentimes, we find ourselves being more concerned with data being changed and not so concerned about who can read it. When this is the case, it is possible to implement a private setter. A private setter allows us to limit write access to within the scope of the struct
but still allow the property to be read outside of the struct
.
We use the (set)
keyword when we want to declare a private setter:
struct Cat { private(set) var numberOfLives : Int }
In this example, we declare the setter to have private level access, while the getter will be the default internal
level access. Note that we could have also declared the numberOfLives
variable like so:
struct Cat { public private(set) var numberOfLives : Int = 9 } var scrambles = Cat() // Prints: 9 print(scrambles.numberOfLives) // This causes a compiler error due to invalid access scrambles.numberOfLives = 10
This gives the getter for numberOfLives
public level access, while the setter has private level access. Any combination of access levels can be declared, as long as the setter has a lower access level than the getter. For example open fileprivate(set)
is a valid access level, while private internal(set)
would be an invalid access level.
Instructions
Define the paperclipSales
variable to have a private
setter and an internal
getter.
Use the dot syntax to print the value of paperclipSales
to the console using the alphaOffice
instance.
Use the dot syntax to attempt to set the value of paperclipSales
. You should get an error!
Comment the offending line out so that our code will run again.