title: Swift Struct Memory Leak
body: <p>We're trying to use Swift structs where we can. We are also using RxSwift which has methods which take closures. When we have a struct that creates a closure that refers to <strong>self</strong>, that creates a <a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html" rel="noreferrer">strong reference cycle</a>.</p>
  
  <pre><code>import Foundation
  import RxSwift
  
  struct DoesItLeak {
  
      var someState: String = "initial value"
      var someVariable: Variable&lt;String&gt; = Variable("some stuff")
  
      let bag = DisposeBag()
  
      mutating func someFoo() {
  
          someVariable.subscribeNext { person in
  
              self.someState = "something"
          }
          .addDisposableTo(bag)
      }
  }
  </code></pre>
  
  <p>How do I know this? If I create 100,000 DoesItLeak objects and call someFoo() on each of them, I believe I have 100,000 objects with strong reference cycles. In other words, when I get rid of the DoesItLeak array containing those objects, the objects stay in memory. If I do not call someFoo(), there is no problem. </p>
  
  <p>Variable is a class. So, I can see this memory issue by using xcode's Instruments' Allocations and filtering in <strong>Variable&lt; String ></strong> </p>
  
  <p><a href="https://i.stack.imgur.com/DYvDY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DYvDY.png" alt="Filtering By Variable"></a></p>
  
  <p><a href="https://i.stack.imgur.com/4wb98.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4wb98.png" alt="enter image description here"></a></p>
  
  <p>If I try to use [weak self] such as in the following, I get a compiler error:</p>
  
  <pre><code>someVariable.subscribeNext { [weak self] person in
  </code></pre>
  
  <p>The compiler error is "weak cannot be applied to non-class type" </p>
  
  <p>In real/non-example code, we access methods and variables via self and it's a memory issue.</p>
  
  <p><strong>How can I resolve this memory issue while keeping the DoesItLeak a struct?</strong> </p>
  
  <p>Thanks for your help.</p>