Skip to content

Instantly share code, notes, and snippets.

@mukyasa
Created June 6, 2020 08:05
Show Gist options
  • Save mukyasa/f5592d0bf27808b394b92a1531f86dda to your computer and use it in GitHub Desktop.
Save mukyasa/f5592d0bf27808b394b92a1531f86dda to your computer and use it in GitHub Desktop.
@propertyWrapper
struct CodableUserDefaultsBacked<T: Codable> {
let key: String
let defaultValue: T
var storage: UserDefaults = .standard
var wrappedValue: T {
get {
return CodableStorageHelper<T>.getValueFor(key: key, storage: storage) ?? defaultValue
}
set {
if let optional = newValue as? AnyOptional,
optional.isNil {
storage.removeObject(forKey: key)
} else {
CodableStorageHelper<T>.setValue(newValue,
key: key,
storage: storage)
}
}
}
}
// UserDefaults Generic Helper Storage
// to save Codable(custom object) in only STANDARD defaults
enum CodableStorageHelper<T: Codable> {
static func setValue(_ value: T,
key: String,
storage: UserDefaults = .standard) {
// Convert newValue to data
let data = try? JSONEncoder().encode(value)
// Set value to UserDefaults
storage.set(data, forKey: key)
storage.synchronize()
}
static func getValueFor(key: String,
storage: UserDefaults = .standard) -> T? {
// Read value from UserDefaults
guard let data = storage.object(forKey: key) as? Data else {
// Return defaultValue when no data in UserDefaults
return nil
}
// Convert data to the desire data type
let value = try? JSONDecoder().decode(T.self, from: data)
return value ?? nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment