iosswiftaccessor

In Swift, is there a better way to initialize a "get" only variable?


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?


Solution

  • 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
        }        
    }