Skip to content

Instantly share code, notes, and snippets.

Created December 17, 2018 19:04
What would you like to do?
// Persistable.swift
import Foundation
import Disk
public protocol Persistable: Codable {
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?, 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