title: Pointers, Pointer Arithmetic, and Raw Data in Swift
body: <p>My application uses a somewhat complex inmutable data structure that is encoded in a binary file. I need to have access to it at the byte level, avoiding any copying. Normally, I would use C or C++ pointer arithmetic and typecasts, to access and interpret the raw byte values. I would like to do the same with Swift.</p>
  
  <p>I have found that the following works:</p>
  
  <pre><code>class RawData {
      var data: NSData!
  
      init(rawData: NSData) {
        data = rawData
      }
  
      func read&lt;T&gt;(byteLocation: Int) -&gt; T {
        let bytes = data.subdataWithRange(NSMakeRange(byteLocation, sizeof(T))).bytes
        return UnsafePointer&lt;T&gt;(bytes).memory
      }
  
      func example_ReadAnIntAtByteLocation5() -&gt; Int {
        return read(5) as Int
      }
  }
  </code></pre>
  
  <p>However, I am not sure how efficient it is. Do <code>data.subdataWithRange</code> and <code>NSMakeRange</code> allocate objects every time I call them, or are they just syntactic sugar for dealing with pointers?</p>
  
  <p>Is there a better way to do this in Swift?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I have created a small Objective-C class that just encapsulates a function to offset a pointer by a given number of bytes:</p>
  
  <pre><code>@implementation RawDataOffsetPointer
  
  inline void* offsetPointer(void* ptr, int bytes){
      return (char*)ptr + bytes;
  }
  
  @end
  </code></pre>
  
  <p>If I include this class in the bridging header, then I can change my <code>read</code> method to</p>
  
  <pre><code>func read&lt;T&gt;(byteLocation: Int) -&gt; T {
    let ptr = offsetPointer(data.bytes, CInt(byteLocation))
    return UnsafePointer&lt;T&gt;(ptr).memory
  }
  </code></pre>
  
  <p>which will not copy data from my buffer, or allocate other objects.</p>
  
  <p>However, it would still be nice to do some pointer arithmetic from Swift, if it were possible.</p>