title: Setting requirements for class variables in Swift
body: <p>I am new to swift. In a group of classes / subclasses, I would like a variable in the super class to be within a required range.  For example, in the following code.</p>
  
  <pre><code>class Vehicle {
      var speed: Int
      var heading: Int
  
      init(speed: Int, heading: Int) {
          self.speed = speed
          self.heading = heading
      }
  
      func turnRight() {
          if 360 - heading &lt; 90 {
              heading = heading - 270
          } else {
              heading = heading + 90
          }
      }
  }
  
  class Car : Vehicle {
      init(speed: Int, heading: Int) {
          super.init(speed: speed, heading: heading)
      }
  
      override func turnRight() {
          speed = speed / 2
          if 360 - heading &lt; 90 {
              heading = heading - 270
          } else {
              heading = heading + 90
          }
      }
  }
  </code></pre>
  
  <p>What I don't like about the above, is that if I'm creating more subclasses for car, I'll always be forced to check that heading is within 0 and 360.  I know about getters and setters, but is there a way to use a setter and still support incrementing the variable?</p>
  
  <p>Ideally, I want my turnRight functions to look like:</p>
  
  <pre><code>func turnRight() {
      heading = heading + 90
  }
  
  override func turnRight() {
      speed = speed / 2
      heading = heading + 90
  }
  </code></pre>
  
  <p>...and for my variable set in the superclass to ensure that the heading is within 0 and 360.</p>