Last active
January 24, 2019 11:25
-
-
Save cemolcay/0beab820174499b94f4370a8e08a37e0 to your computer and use it in GitHub Desktop.
A protocol where can read/write Codable items on disk.
This file contains hidden or 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
protocol DictionaryStore { | |
static var storeFileName: String { get } | |
var store: [[String: Any]] { get set } | |
} | |
extension DictionaryStore { | |
func write() throws { | |
let data = try JSONSerialization.data(withJSONObject: store, options: []) | |
let document = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) | |
let path = document.appendingPathComponent(Self.storeFileName) | |
try data.write(to: path) | |
} | |
func read() throws -> [[String: Any]] { | |
let document = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) | |
let path = document.appendingPathComponent(Self.storeFileName) | |
let data = try Data(contentsOf: path) | |
return (try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]]) ?? [] | |
} | |
} | |
protocol CodableStore { | |
associatedtype StoreType: Codable | |
static var storeFileName: String { get } | |
var store: [StoreType] { get set } | |
} | |
extension CodableStore { | |
func write() throws { | |
let encoder = JSONEncoder() | |
let data = try encoder.encode(store) | |
let document = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) | |
let path = document.appendingPathComponent(Self.storeFileName) | |
try data.write(to: path) | |
} | |
func read() throws -> [StoreType] { | |
let decoder = JSONDecoder() | |
let document = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) | |
let path = document.appendingPathComponent(Self.storeFileName) | |
let data = try Data(contentsOf: path) | |
return try decoder.decode([StoreType].self, from: data) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment