Last active
October 19, 2019 05:52
-
-
Save laevandus/c49dad3acff865440f9e47d7100b524f 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
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 = storage.map { (keyValuePair) -> (String, [Data]) in | |
return (keyValuePair.key.rawValue, keyValuePair.value.map({ $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