Skip to content

Instantly share code, notes, and snippets.

@laevandus
Last active October 19, 2019 05:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laevandus/c49dad3acff865440f9e47d7100b524f to your computer and use it in GitHub Desktop.
Save laevandus/c49dad3acff865440f9e47d7100b524f to your computer and use it in GitHub Desktop.
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