title: Using Getters and Setters to modify values w/o Subclassing in Swift
body: <p>Let's say I have a class, and when I set its property, I want it to append that property with a file type like <code>.fileType</code>:</p>
  <pre><code>class File {
      var fileName: String {
      get {
          return self.fileName
      }
      set {
          self.fileName = fileName + &quot;.fileType&quot;
      }
      }
  }
  </code></pre>
  <p>Which I try to use like this:</p>
  <pre><code>let newFile = File()
  newFile.fileName = &quot;My File&quot;
  </code></pre>
  <p>Unfortunately, the variable never sets:</p>
  <p><img src="https://i.stack.imgur.com/VO5Bn.png" alt="Checkpoints" /></p>
  <p>I have two possible workarounds.</p>
  <h3> Option 1: Observe Value After Set </h3>
  <pre><code>class File {
      var fileName: String = &quot;&quot; {
      didSet {
          self.fileName += &quot;.fileType&quot;
      }
      }
  }
  
  let file = File()
  file.fileName = &quot;SomeName&quot; // SomeName.fileType
  </code></pre>
  <p>But with this, I must wait until the value is already set before I can modify it.  For this particular example, it doesn't make too much difference; however, I'd like to be able to avoid this.</p>
  <h3> Option 2: Subclass </h3>
  <p>This solution is based on the example <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Inheritance.html#//apple_ref/doc/uid/TP40014097-CH17-XID_265" rel="nofollow noreferrer">here.</a>  Search for 'speedLimitedCar'</p>
  <pre><code>class File {
      var fileName = &quot;&quot;
  }
  
  class SubFile: File {
  
      override var fileName: String {
      get {
          return super.fileName
      }
      set {
          super.fileName = newValue + &quot;.fileType&quot;
      }
      }
  }
  
  let subfile = SubFile()
  subfile.fileName = &quot;Hello&quot; // Hello.fileType
  </code></pre>
  <h3> Question </h3>
  <p>I could also just create a secondary property to store the value and access that in the fileName's getter/setter, but is there a way to avoid all that and modify a property directly within its getter / setter?</p>