title: Nested write transactions in Realm Swift
body: <p>When I build methods that update a realm object I always have the dilemma if it's better to put the <code>write</code>/<code>beginWrite</code> inside the method to gain atomicity and keep the callers clean, or in the caller to avoid the risk of nesting transactions.</p>
  
  <p>For this reason I was thinking a way to nest transactions without risks and I made this function taking the original <code>write</code> and modifying it a bit:</p>
  
  <pre><code>extension Realm {
      func writeNested(_ block: (() throws -&gt; Void)) throws {
          let isNested = isInWriteTransaction
          if !isNested { beginWrite() }
          do {
              try block()
          } catch let error {
              if isInWriteTransaction { cancelWrite() }
              throw error
          }
          if !isNested &amp;&amp; isInWriteTransaction { try commitWrite() }
      }
  }
  </code></pre>
  
  <p>Is there any downside I didn't think about?</p>