Last active
March 1, 2024 09:55
-
-
Save MojtabaHs/ba244569e1db8a2f2ea4cb5c0d409af3 to your computer and use it in GitHub Desktop.
A property. wrapper for store/restore variables backed by the given user defaults.
This file contains 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
import Foundation | |
@propertyWrapper | |
public struct UserDefaultStorage<T: Codable> { | |
private let key: String | |
private let defaultValue: T | |
private let userDefaults: UserDefaults | |
public init(key: String, default: T, store: UserDefaults = .standard) { | |
self.key = key | |
self.defaultValue = `default` | |
self.userDefaults = store | |
} | |
public var wrappedValue: T { | |
get { | |
guard let data = userDefaults.data(forKey: key) else { return defaultValue } | |
do { | |
let value = try JSONDecoder().decode(T.self, from: data) | |
return value | |
} catch { | |
assertionFailure(error.localizedDescription) | |
return defaultValue | |
} | |
} | |
set { | |
let data: Data? | |
do { | |
data = try JSONEncoder().encode(newValue) | |
} catch { | |
assertionFailure(error.localizedDescription) | |
data = nil | |
} | |
userDefaults.set(data, forKey: key) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment