Last active
May 21, 2022 22:30
-
-
Save rudifa/6addff65be5015f089d84fa88732b869 to your computer and use it in GitHub Desktop.
BackupFile.swift
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
// | |
// 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