title: Swift memoizing/caching lazy variable in a struct
body: <p>I drank the struct/value koolaid in Swift. And now I have an interesting problem I don't know how to solve. I have a struct which is a container, e.g.</p>
  
  <pre><code>struct Foo {
      var bars:[Bar]
  }
  </code></pre>
  
  <p>As I make edits to this, I create copies so that I can keep an undo stack. So far so good. Just like the good tutorials showed. There are some derived attributes that I use with this guy though:</p>
  
  <pre><code>struct Foo {
      var bars:[Bar]
  
      var derivedValue:Int {
          ...
      }
  }
  </code></pre>
  
  <p>In recent profiling, I noticed a) that the computation to compute derivedValue is kind of expensive/redundant b) not always necessary to compute in a variety of use cases.</p>
  
  <p>In my classic OOP way, I would make this a memoizing/lazy variable. Basically, have it be nil until called upon, compute it once and store it, and return said result on future calls. Since I'm following a "make copies to edit" pattern, the invariant wouldn't be broken.</p>
  
  <p>But I can't figure out how to apply this pattern if it is struct. I can do this:</p>
  
  <pre><code>struct Foo {
      var bars:[Bar]
      lazy var derivedValue:Int = self.computeDerivation()
  }
  </code></pre>
  
  <p>which works, until the struct references that value itself, e.g.</p>
  
  <pre><code>struct Foo {
      var bars:[Bar]
      lazy var derivedValue:Int = self.computeDerivation()
  
      fun anotherDerivedComputation() {
          return self.derivedValue / 2
      }
  }
  </code></pre>
  
  <p>At this point, the compiler complains because <code>anotherDerivedComputation</code> is causing a change to the receiver and therefore needs to be marked <code>mutating</code>. That just feels wrong to make an accessor be marked mutating. But for grins, I try it, but that creates a new raft of problems. Now anywhere where I have an expression like</p>
  
  <pre><code>XCTAssertEqaul(foo.anotherDerivedComputation(), 20)
  </code></pre>
  
  <p>the compiler complains because a parameter is implicitly a non mutating let value, not a var.</p>
  
  <p>Is there a pattern I'm missing for having a struct with a deferred/lazy/cached member?</p>