Manifesto: Adding memory ownership to Swift
I&#x27;m at work and went diving into the doc looking for one specific thing. I found it, but it turns out to be a put unfortunate.<p><a href="https:&#x2F;&#x2F;github.com&#x2F;apple&#x2F;swift&#x2F;blob&#x2F;master&#x2F;docs&#x2F;OwnershipManifesto.md#deinit-for-non-copyable-types" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;apple&#x2F;swift&#x2F;blob&#x2F;master&#x2F;docs&#x2F;OwnershipMan...</a><p>&gt; Swift is permitted to destroy a value (and thus call deinit) at any time between its last use and its formal point of destruction. The exact definition of &quot;use&quot; for the purposes of this definition is not yet fully decided.<p>For things like scoped lockables the last &quot;use&quot; must be well defined with respect to the termination of the scope. Early deinit means you&#x27;re still unable to build something like C++&#x27;s std::lock_guard (<a href="http:&#x2F;&#x2F;en.cppreference.com&#x2F;w&#x2F;cpp&#x2F;thread&#x2F;lock_guard" rel="nofollow">http:&#x2F;&#x2F;en.cppreference.com&#x2F;w&#x2F;cpp&#x2F;thread&#x2F;lock_guard</a>).<p>Consider:<p><pre><code>    &#x2F;&#x2F; dwizzles can be fizzled up to three times, but no more.
    class dwizzle {
     public:
      dwizzle() : count_(0) {}

      void fizzle() {
        std::lock_guard lock(&amp;mutex_);
        if (count_ &gt;= 3) return;
        ++count_;
      }  
     private:
      std::mutex mutex_;
      int count_ = 0;
    };
</code></pre>
Obviously a silly toy, but the point is that we acquire the lock, we must hold it until the end of the scope for correctness, and we want to ensure it&#x27;s dropped on early returns.<p>I hope any formal proposal coming out of this has a sufficiently strict definition of &quot;use&quot; (or provides opt-in tools for building structs that restrict the definition appropriately) to allow such constructions. It&#x27;s much nicer than having to always type something like:<p><pre><code>    mutex.lock()
    defer {
      mutex.unlock()
    }
</code></pre>
(apologies for any inconsistency in my C++ above -- the codebase I routinely work in has its own mutex type and an equivalent scoped lockable -- I tried to adopt the more standard version for universality&#x27;s sake).