Skip to content

Instantly share code, notes, and snippets.

@hirad
Created June 1, 2020 19:44
Show Gist options
  • Save hirad/06f6831dbfa56a1f5e9c752bb1114a78 to your computer and use it in GitHub Desktop.
Save hirad/06f6831dbfa56a1f5e9c752bb1114a78 to your computer and use it in GitHub Desktop.
Compiler crasher
import Foundation
import Combine
private let docsDirURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
@propertyWrapper
struct Persisted<Value: Codable> {
let fileName: String
let defaultValue: Value
private let encoder = JSONEncoder()
private let decoder = JSONDecoder()
private var inMemoryValue: Value?
init(fileName: String, defaultValue: Value) {
self.fileName = fileName
self.defaultValue = defaultValue
}
private var storageURL: URL {
return docsDirURL.appendingPathComponent(fileName)
}
var wrappedValue: Value {
mutating get {
if let v = inMemoryValue {
return v
}
let v = read(from: storageURL) ?? defaultValue
inMemoryValue = v
return v
}
set {
inMemoryValue = newValue
write(newValue, to: storageURL)
}
}
private func read(from url: URL) -> Value? {
let data = try! Data(contentsOf: url)
let decoded = try? decoder.decode(Value.self, from: data)
return decoded
}
private func write(_ value: Value, to url: URL) {
let data = try! encoder.encode(value)
try! data.write(to: url)
}
}
class PersistenceStore {
@Persisted(fileName: "strings", defaultValue: [])
private var _strings: [String]
@Published private(set) var strings: [String]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment