title: Swift Struct with Lazy, private property conforming to Protocol
body: <p>First, I have a protocol that defines only a few, readonly properties, ex:</p>
  
  <pre><code>protocol Example {
    var var1:String { get }
    var varArray:[String] { get }
  }
  </code></pre>
  
  <p>I then want to create a struct that conforms to that protocol.  The problem I'm running into, is that I have two conflicting requirements:</p>
  
  <ol>
  <li>The properties need to be lazily generated.  </li>
  <li>The properties are related and need to be generated together.</li>
  </ol>
  
  <p>I can't seem to find a way to do this.  The closest I've come is something like this:</p>
  
  <pre><code>struct AStruct : Example {
    private lazy var data:(var1:String, varArray:[String]) = {
      var stringValue:String = ""
      var stringArray:[String] = []
      //Generate data
      return (stringValue, stringArray)
    }()
  
    var var1:String {
      return self.data.var1
    }
  
    var varArray:[String] {
      return self.data.varArray
    }
  }
  </code></pre>
  
  <p>The problem is, I'm getting the error: <code>Immutable value of type 'AStruct' only has mutating members named 'data'</code>.</p>
  
  <p>Does anyone know of a way I might be able to accomplish my goal?  Technically, the <code>data</code> variable is mutable but will never change.  I can't use <code>let</code> with <code>lazy</code> so I can't specify that the value will never change once it's been generated.  I need the values to be generated though, because the struct is created on the main thread, but the values will be generated on a background thread by another process altogether.  </p>
  
  <h3>Update</h3>
  
  <p>So it was pointed out to me that I can make the getters <code>mutating</code> in both the protocol and the struct.  That works, except I now have the problem that I cannot use this struct in any other struct (which I am).  So in the end, I've pushed off the problem into another struct, which I do not want to be mutable.</p>
  
  <p>Ex:</p>
  
  <pre><code>struct Container {
    let astruct:AStruct
    let callback:() -&gt; ()
  }
  </code></pre>
  
  <p>I cannot access the variables in <code>AStruct</code> from <code>Container</code> because <code>Container</code> is immutable and the member variables of <code>AStruct</code> are mutating.  Trying to access them gives me the same error message I spoke of earlier.</p>
  
  <p>Changing the container to use <code>var</code> instead of <code>let</code> yields the same error:</p>
  
  <pre><code>struct Container {
    var astruct:AStruct
    let callback:() -&gt; ()
  }
  </code></pre>
  
  <p>If I set up a function in the processing class that receives a <code>Container</code> to process:</p>
  
  <pre><code>func processContainer(cont:Container){
    self.doSomething(cont.astruct.var1)
  }
  </code></pre>
  
  <p>I get the same error: <code>Immutable value of type 'AStruct' only has mutating members names 'sql'</code>.</p>