Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
struct EventItem: ContainerItem, Codable {
let date: Date
let title: String
let description: String
struct NoteItem: ContainerItem, Codable {
let text: String
enum CalendarKeys: String {
case homeEvents, workEvents, notes
extension Container where Key == CalendarKeys {
convenience init(contentsOfURL url: URL) throws {
let data = try Data(contentsOf: url)
let contents = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as! [Key.RawValue: [Data]]
let converted = contents.compactMap({ (keyValuePair) -> (Key, [ContainerItem])? in
guard let key = Key(rawValue: keyValuePair.key) else { return nil }
switch key {
case .homeEvents, .workEvents:
return (key, keyValuePair.value.compactMap({ EventItem(jsonData: $0) }))
case .notes:
return (key, keyValuePair.value.compactMap({ NoteItem(jsonData: $0) }))
self.init(content: Dictionary(uniqueKeysWithValues: converted))
extension Container where Key.RawValue == String {
func write(to url: URL) throws {
let converted = { (keyValuePair) -> (String, [Data]) in
return (keyValuePair.key.rawValue,{ $0.jsonDataRepresentation }))
let data = try NSKeyedArchiver.archivedData(withRootObject: Dictionary(uniqueKeysWithValues: converted), requiringSecureCoding: false)
try data.write(to: url, options: .atomicWrite)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment