Forked from nubbel/Swift: Convert structs and enums to NSData and vice-versa
Created
October 4, 2016 04:26
-
-
Save adamnemecek/526179a15d2bad0084da91a7a5ffa8b3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment