Say I have a class, MyClass, and it can be in either a valid or invalid state. So I keep track of this with a bool called isValid. I want this value initialized to false until the class's initialize function is called. The initialize (and a corresponding reset function) will directly be able to change the value of the isValid bool. This is what I have set up so far:
class MyClass {
private var _isValid: Bool = false
var isValid: Bool {
get { return _isValid }
}
// any required init functions
func initialize() {
// init stuff
_isValid = true
}
func reset() {
// reset stuff
_isValid = false
}
}
So is this the best way to do it, or is there any way I can remove the second private var and somehow allow just the class functions to modify a read only public facing variable?
Just make your setter private. See Access Control.
class MyClass {
private(set) var isValid = false
func initialize() {
// init stuff
self.isValid = true
}
func reset() {
// reset stuff
self.isValid = false
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With