Skip to content

Instantly share code, notes, and snippets.

@mattyoung
Last active November 13, 2017 17:10
Show Gist options
  • Save mattyoung/5543bf4b0680498a3e15941247fa4349 to your computer and use it in GitHub Desktop.
Save mattyoung/5543bf4b0680498a3e15941247fa4349 to your computer and use it in GitHub Desktop.
import Foundation
struct Person: Codable {
let name: String
}
let person = Person(name: "Paul")
if #available(macOS 10.12, *) {
let filePath = URL(fileURLWithPath: "Archiving File")
let archiver = NSKeyedArchiver()
try archiver.encodeEncodable(person, forKey: NSKeyedArchiveRootObjectKey)
try archiver.encodedData.write(to: filePath)
//archiver.finishEncoding() // this is unnecessary, .encodedData calls this implicitly
// attempt to read the thing back
let data = try Data(contentsOf: filePath)
let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
//// .decodeDecodable(...) works, too..., but it does not throw,
//// it sets .error
////if let someone = unarchiver.decodeDecodable(Person.self, forKey: NSKeyedArchiveRootObjectKey) {
if let someone = try unarchiver.decodeTopLevelDecodable(Person.self, forKey: NSKeyedArchiveRootObjectKey) {
print("Paul is resurrected...")
dump(someone)
} else {
print("Unable to read person back, Paul is gone forever :(")
}
unarchiver.finishDecoding() // notify delegate decode is done
} else {
print("Your macOS is too old to run this thing, must be at least ver. 10.12")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment