Created
June 6, 2020 08:05
-
-
Save mukyasa/f5592d0bf27808b394b92a1531f86dda to your computer and use it in GitHub Desktop.
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
@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