Skip to content

Instantly share code, notes, and snippets.

@jurvis
Created August 15, 2020 17:41
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 jurvis/789e2f90c5c1ce5834619b49771bc27f to your computer and use it in GitHub Desktop.
Save jurvis/789e2f90c5c1ce5834619b49771bc27f to your computer and use it in GitHub Desktop.
Swift Property Wrapper for Saving Values to JSON in Documents Directory
@propertyWrapper struct DocDirectoryBacked<Value: Codable> {
let location: String
let documentDirectory = try! FileManager.default.url(for: .libraryDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
private var dirToSave: URL {
return documentDirectory.appendingPathComponent("\(location).json")
}
var wrappedValue: Value? {
get {
do {
let data = try Data(contentsOf: dirToSave)
return try JSONDecoder().decode(Value.self, from: data)
} catch {
return nil
}
}
set {
do {
let data = try JSONEncoder().encode(newValue)
try data.write(to: dirToSave)
} catch {
print("Error saving to \(dirToSave)")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment