title: Guarantees about the lifetime of a reference in a local variable
body: <p>In <em>Swift</em>, I can use the <em>ARC</em> mechanism to manage the lifetime of resources external to the process because instances of classes are de-initialized predictably. This is in contrast to environments like the <em>Java</em> Runtime where instances are de-initialized when the garbage collector collects the object, which is not guaranteed to happen in a defined time window.</p>
  
  <p>But what are the exact guarantees that the Swift language and runtime make about the lifetime of instances when those instances are referenced by local variables? E.g. what is the earliest point that an instance may be deallocated, when a local variable is holding the only reference to it?</p>
  
  <p>In the following example, I am creating an instance of a class and store a reference to it in a local variable.</p>
  
  <pre><code>public final class Something {
      init() { print("something.init()") }
      deinit { print("something.deinit()") }
  }
  
  func useSomething() {
      let something = Something()
      print("useSomething()")
  }
  
  useSomething()
  </code></pre>
  
  <p>The variable is not used after the point where I print <code>useSomething()</code> but <code>deinit</code> runs consistenly <em>after</em> that call to <code>print()</code>:</p>
  
  <pre><code>$ swift run -c release
  something.init()
  useSomething()
  something.deinit()
  </code></pre>
  
  <p>It seems that references are always decremented at the point where the variable goes out of scope. Wrapping the variable declaration in a <code>do</code> block changes the order:</p>
  
  <pre><code>func useSomething() {
      do { let something = Something() }
      print("useSomething()")
  }
  </code></pre>
  
  <p></p>
  
  <pre><code>$ swift run -c release
  something.init()
  something.deinit()
  useSomething()
  </code></pre>
  
  <p>Is this order guaranteed or can it change with a different compiler or optimization level?</p>
  
  <hr>
  
  <p>The reason I'm interested in this is that I want to wrap C APIs in object-oriented Swift APIs and would like to automatically manage the lifetime of resources allocated using a C API using Swift classes and reference counting. This works great if every usage of the C API requires a reference to the resource it operates on because I know that the Swift instance will live at least until the last call that operates on the resource that instance is representing.</p>
  
  <p>But some APIs use global state to select a resource and subsequent calls to the API do not require a reference to the resource to be passed and implicitly operate on the selected resource instead. OpenGL's <code>glDrawElements()</code> implicitly uses maybe 5 or 10 such resources (vertex arrays, shaders, frame buffers, textures …).</p>