Skip to content

Instantly share code, notes, and snippets.

@rudifa
Last active May 21, 2022 22:30
Show Gist options
  • Save rudifa/6addff65be5015f089d84fa88732b869 to your computer and use it in GitHub Desktop.
Save rudifa/6addff65be5015f089d84fa88732b869 to your computer and use it in GitHub Desktop.
BackupFile.swift
//
// BackupFile.swift
// BackupFile
//
// Created by Rudolf Farkas on 21.05.22.
//
import Foundation
// a wrapper struct that backs up the wrapped struct in an iOS file
public struct BackupFile<Wrapped: Codable>: Codable {
public let wrapped: Wrapped
public init(wrapped: Wrapped) {
self.wrapped = wrapped
}
}
public extension FileManager {
func backupFile<Wrapped: Codable>(at url: URL, with wrapped: Wrapped) throws {
let backupFile = BackupFile(wrapped: wrapped)
try backupFile.write(to: url)
}
func restoreFile<Wrapped: Codable>(at url: URL) throws -> Wrapped {
let backupFile = try BackupFile<Wrapped>(from: url)
return backupFile.wrapped
}
}
public extension BackupFile {
init(from url: URL) throws {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
self = try decoder.decode(BackupFile.self, from: data)
}
func write(to url: URL) throws {
let encoder = JSONEncoder()
let data = try encoder.encode(self)
try data.write(to: url)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment