Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Archiving of value types in Swift
import Foundation
struct Car {
var number: Int
}
protocol Archivable {
func archive() -> NSData
static func unarchive(data: NSData) -> Self?
}
extension Car: Archivable {
func archive() -> NSData {
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
archiver.outputFormat = NSPropertyListFormat.XMLFormat_v1_0
archiver.encodeInteger(number, forKey:"number")
archiver.finishEncoding()
return data
}
static func unarchive(data: NSData) -> Car? {
let unarchiver = NSKeyedUnarchiver(forReadingWithData: data)
let number = unarchiver.decodeIntegerForKey("number")
return Car(number: number)
}
}
let a = Car(number: 5)
let data = a.archive()
let b = Car.unarchive(data)
b?.number
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment