title: Serialization of Structs to NSData in Swift
body: <p>I need to save a Swift struct to <code>NSData</code>. I can't conform to <code>NSCoding</code> since it only works for subclasses of <code>NSObject</code>.</p>
  
  <p>I wrote a little <code>protocol</code> with extensions in Swift 2.0 that seems to work in a Playground. It seems a little <em>too</em> easy.</p>
  
  <p>Is there something here I am missing?</p>
  
  <p>The following code can be run in a playground in Xcode 7 Beta 5.</p>
  
  <pre><code>//: Playground - noun: a place where people can play
  
   import UIKit
  
  
  protocol Serializable {
      init?(encodedData: NSData)
      var encodedData: NSData { get }
  }
  
  extension Serializable {
  
      var encodedData: NSData {
          var pointer = self
          return NSData(bytes: &amp;pointer, length: sizeof(Self.self))
      }
  
      init?(encodedData data: NSData) {
          guard
              data.length == sizeof(Self.self)
              else { return nil }
  
          self = UnsafePointer(data.bytes).memory
      }
  }
  
  struct Test: CustomStringConvertible, Serializable {
      let message: String
      let people: [String]
      let color: UIColor
  
      var description: String {
          return "\(message) + \(people) + \(color)"
      }
  }
  
  let structToEncode = Test(message: "Hi!", people: ["me", "someone else"], color: UIColor(red: 0.5, green: 0.2, blue: 0.1, alpha: 0.4))
  let encodedData = structToEncode.encodedData
  let decodedStruct = Test(encodedData: encodedData)
  </code></pre>