Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 53 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save nubbel/5b0a5cb2bf6a2e353061 to your computer and use it in GitHub Desktop.
Save nubbel/5b0a5cb2bf6a2e353061 to your computer and use it in GitHub Desktop.
func encode<T>(var value: T) -> NSData {
return withUnsafePointer(&value) { p in
NSData(bytes: p, length: sizeofValue(value))
}
}
func decode<T>(data: NSData) -> T {
let pointer = UnsafeMutablePointer<T>.alloc(sizeof(T.Type))
data.getBytes(pointer)
return pointer.move()
}
// Example:
enum Result<T> {
case Success(T)
case Failure
}
var res: Result<String> = .Success("yeah")
var data = encode(res)
var decoded: Result<String> = decode(data)
switch decoded {
case .Failure:
"failure"
case .Success(let v):
"success: \(v)" // => "success: yeah"
}
@rob5408
Copy link

rob5408 commented Jun 22, 2015

Great gist! With the deprecation of getBytes, should line 9 be...

data.getBytes(pointer, length: sizeof(T.Type))

@rob5408
Copy link

rob5408 commented Jun 24, 2015

Also, this seems to cause crashes if you have Strings in your struct.

@laszlokorte
Copy link

@rob5408 works if you replace sizeof(T.Type) with just sizeof(T)

@stvalentin
Copy link

thank you
i also was trying to figure this out in the last days and now is working like a charm

@rob5408
Copy link

rob5408 commented Jul 12, 2015

@laszlokorte Thanks! As soon as I read your fix I realized how obvious it was. That said I would have NEVER figure that out. With Swift you get yourself thinking you don't have to worry about pointers then you let them in and immediately shoot your foot off.

@getaaron
Copy link

getaaron commented Oct 2, 2015

I added a little error handling — see here.

@Kalvin126
Copy link

I have an NSArray of Struct of which I writeToFile after encode each struct. If I read the saved plist in the same instance, I can read the data back perfectly but when I rerun and reload the data, it only partially decodes each struct. What gives?

@JoshuaKaden
Copy link

Awesome; thank you!

@100mango
Copy link

It won't work, if you have an array in your struct.

@RollingGoron
Copy link

Any reason why you would want to use this over Struct to NSData via NSJSONSerilization?

@Nathan187
Copy link

Yes, this use to work for me too. It works on simple structs but as it get more complex, nil is always returned. Anyone else experience this?

@bruno-rocha-movile
Copy link

It seems to fail sometimes, returns nil once in a while even without changing anything on the struct

@nullpixel
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment