title: How to save CGImage to Data in Swift?
body: <p>This code type checks and compiles but then crashes. How do I save a <code>CGImage</code> to <code>Data</code> so that I can read it in again later.</p>
  
  <pre><code>let cgi: CGImage? = ...        
  var mData = Data()
  let imageDest = CGImageDestinationCreateWithData(mData as! CFMutableData, 
                                                   kUTTypePNG, 1, nil)!
  CGImageDestinationAddImage(imageDest, cgi!, nil)
  CGImageDestinationFinalize(imageDest)
  </code></pre>
  
  <p>The last line crashes. Error in console is:</p>
  
  <pre><code>2018-01-17 19:25:43.656664-0500 HelloPencil[2799:3101092] -[_NSZeroData 
    appendBytes:length:]: unrecognized selector sent to instance 0x1c80029c0
  2018-01-17 19:25:43.658420-0500 HelloPencil[2799:3101092] *** Terminating app 
    due to uncaught exception 'NSInvalidArgumentException', reason: 
    '-[_NSZeroData appendBytes:length:]: unrecognized selector 
    sent to instance 0x1c80029c0'
  </code></pre>
  
  <p>That cast from <code>Data</code> to <code>CFMutableData</code> was recommended by Xcode, but maybe it's wrong.</p>