Created
August 15, 2020 17:41
-
-
Save jurvis/789e2f90c5c1ce5834619b49771bc27f to your computer and use it in GitHub Desktop.
Swift Property Wrapper for Saving Values to JSON in Documents Directory
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
@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