title: What's an elegant way to do, or fake, 'type punning' in Swift
body: <p>Writing in Swift, I have a specific need that might be a candidate for type punning.  I'm reading files from a disk image where they exist in contiguous 512 byte sectors.  A file comes off the disk as a <code>Data</code> struct which is easily converted to a byte array and/or 512 byte <code>DataSlices</code> without making copying necessary.</p>
  
  <p>So far, so good!  A file can be represented quickly as a collection of arrays containing 512 <code>UInt8</code> units.  However, some disk sectors, typically containing metadata, are better treated as 256 <code>UInt16</code> items.  Ideally, I'd like to be able to refer to the sectors in memory either way without any copying.</p>
  
  <p>Right now, I'm taking a simple approach in which I copy a sector (needing two copies) into something like:</p>
  
  <pre><code>struct Sector {
      let bytes: [UInt8]
      let words: [UInt16]
      . . .
  
  init() {
      self.bytes = Array(repeating: 0, count: 512)
      self.words = Array(repeating: 0, count: 256)
      . . .
  </code></pre>
  
  <p>and then refer to <code>sector.words</code> or <code>sector.bytes</code> depending which is appropriate.  Luckily, the <code>[UInt16]</code> sectors are much fewer than their byte equivalents, so this isn't too awful; and any given sector is one or the other, I don't have to worry that changing <code>bytes</code> doesn't change <code>words</code> (although that's an accident waiting to happen).</p>
  
  <p>Everything I read decries punning the <code>[UInt8]</code> and <code>[UInt16]</code> arrays, and Swift's "unsafe" memory functions are somewhat intimidating.  I'm trying to think of a way to make <code>.words</code> in the above struct occupy the same memory as <code>.bytes</code> and would appreciate some suggestions.</p>
  
  <p>I'm still working on this .. if I find something worthwhile, I'll share.</p>