Created
December 17, 2018 19:04
-
-
Save lacyrhoades/0794ac254620f6133f18649fce42cd02 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
// | |
// Persistable.swift | |
// | |
import Foundation | |
import Disk | |
public protocol Persistable: Codable { | |
init() | |
init?(_: [String: Any]) | |
static func load() -> Self | |
static func save(_ obj: Self) | |
static var persistenceFileName: String { get } | |
} | |
extension Persistable { | |
public static func load() -> Self { | |
if let manager = try? Disk.retrieve(Self.persistencePath, from: .documents, as: Self.self) { | |
return manager | |
} else if let data = try? Disk.retrieve(Self.persistencePath, from: .documents, as: Data.self), | |
let object = try? JSONSerialization.jsonObject(with: data, options: []), | |
let dictionary = object as? [String: Any], | |
let stored = Self.init(dictionary) | |
{ | |
return stored | |
} | |
return Self() | |
} | |
public static func save(_ obj: Self) { | |
try? Disk.save(obj, to: .documents, as: Self.persistencePath) | |
} | |
public static var persistencePath: String { | |
return self.persistenceFileName.appending(".json") | |
} | |
public init?(_: [String: Any]) { | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment