title: How to encode and decode struct to NSData in swift?
body: <p>I have the following struct definition:</p>
  
  <pre class="lang-swift prettyprint-override"><code>struct ThreadManager: Equatable {
    let fid: Int
    let date: NSDate
    let forumName: String
    let typeid: Int
    var page: Int
    var threadList: [Thread]
    var totalPageNumber: Int?
  }
  </code></pre>
  
  <p>and the thread is :</p>
  
  <pre class="lang-swift prettyprint-override"><code>  struct Thread: Equatable {
      let author: Author
      let replyCount: Int
      let readCount: Int
      let title: String
      let tid: Int
      let isTopThread: Bool
      var attributedStringDictionary: [String: NSAttributedString]
      var postDescripiontTimeString: String
      var hasRead: Bool
  }
  </code></pre>
  
  <p>How can I encode a ThreadManager variable to NSData? I tried to used the following functions, but it does not worK.</p>
  
  <pre class="lang-swift prettyprint-override"><code>func encode&lt;T&gt;(var value: T) -&gt; NSData {
    return withUnsafePointer(&amp;value) { p in
      NSData(bytes: p, length: sizeofValue(value))
    }
  }
  
  func decode&lt;T&gt;(data: NSData) -&gt; T {
    let pointer = UnsafeMutablePointer&lt;T&gt;.alloc(sizeof(T))
    data.getBytes(pointer, length: sizeof(T))
  
    return pointer.move()
  }
  </code></pre>
  
  <p>I have ThreadManager items, and I want to store them into sqlite. So I need to convert them to NSData. I have a variable called threadManager, the number of items in its threadList is about 70. I run the code and set a breakpoint, and input encode(threadManager) in xcode console, it is only 73bytes. It is wrong. How can I encode and decode those struct to NSData.</p>