Review this generated property wrapper against the task.
Persist Codable settings without leaking secrets, distinguish missing data from corrupt data, preserve the last good value when encoding fails, and avoid repeated decoding on unchanged reads.
swift
import Foundation
@propertyWrapper
struct JSONSetting<Value: Codable> {
let key: String
let defaultValue: Value
var wrappedValue: Value {
get {
guard let data = UserDefaults.standard.data(forKey: key) else { return defaultValue }
return (try? JSONDecoder().decode(Value.self, from: data)) ?? defaultValue
}
set {
let data = try? JSONEncoder().encode(newValue)
print("saving \(key): \(newValue)")
UserDefaults.standard.set(data, forKey: key)
}
}
init(wrappedValue: Value, _ key: String) {
self.key = key
self.defaultValue = wrappedValue
}
}
generated code is illustrative, not from any one model