Created
June 17, 2015 22:12
-
-
Save marius-serban/249e4f13df097eab2d02 to your computer and use it in GitHub Desktop.
Archiving of value types in Swift
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
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