Skip to content

Instantly share code, notes, and snippets.

@mdb1
Created April 18, 2023 19:12
Show Gist options
  • Save mdb1/2c902ea002c071642ea9dc119633c304 to your computer and use it in GitHub Desktop.
Save mdb1/2c902ea002c071642ea9dc119633c304 to your computer and use it in GitHub Desktop.
UserPreferences: A wrapper for UserDefaults
/// A class that provides a centralized way to access and modify stored preferences.
final class UserPreferences {
static let shared = UserPreferences()
private let userDefaults: UserDefaults
/// Initializes the UserPreferences object with a UserDefaults instance.
init(userDefaults: UserDefaults = .standard) {
self.userDefaults = userDefaults
}
/// Subscript that provides a convenient way to access stored values.
subscript<T>(key: PersistenceKey) -> T? {
get { return userDefaults[key.rawValue] }
set(newValue) {
userDefaults[key.rawValue] = newValue
}
}
/// Removes the stored value for the given key.
func remove(key: PersistenceKey) {
userDefaults.removeObject(forKey: key.rawValue)
userDefaults.synchronize()
}
}
/// Extension on UserDefaults that adds a subscript for convenient access to stored values.
extension UserDefaults {
subscript<T>(key: String) -> T? {
get { return object(forKey: key) as? T }
set(newValue) {
set(newValue, forKey: key)
synchronize()
}
}
}
/// Enumeration of all the keys that are persisted in the UserDefaults.
enum PersistenceKey: String, CaseIterable {
case onBoardingSeen
case defaultCoin
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment