Last active
July 7, 2023 18:28
UserDefaults template with embedded auto-completion
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
let defaults = UserDefaults.standard | |
// MARK: Keys | |
enum Keys: String, CaseIterable { | |
case firstName | |
case websiteUrl | |
case hasLaunchedAppBefore | |
/// The default value for a given UserDefaults key | |
var defaultValue: Any { | |
switch self { | |
case .firstName: return "John" | |
case .websiteUrl: return URL(string: "https://apple.com") | |
case .hasLaunchedAppBefore: return false | |
} | |
} | |
} | |
// MARK: Settings | |
struct Settings { | |
static let firstName: String = getValue(.firstName) as! String | |
static let websiteUrl: URL = getValue(.websiteUrl) as! URL | |
static var hasLaunchedAppBefore: Bool = getValue(.hasLaunchedAppBefore) as! Bool | |
/// Returns the value for a given UserDefaults key | |
static func getValue(_ forKey: Keys) -> Any { | |
return defaults.value(forKey: forKey.rawValue) as Any | |
} | |
/// Saves a value to a given UserDefaults key | |
static func saveValue(_ value: Any, forKey: Keys) { | |
defaults.set(value, forKey: forKey.rawValue) | |
} | |
/// Returns the default value for any given UserDefaults key | |
static func getDefaultValue(_ forKey: Keys) -> Any { | |
return forKey.defaultValue | |
} | |
/// Reverts to the default value of the given UserDefaults key | |
static func setDefaultValue(_ forKey: Keys) { | |
defaults.set(forKey.defaultValue, forKey: forKey.rawValue) | |
} | |
/// Restore all values to their default state | |
static func restoreAllDefaults() { | |
for key in Keys.allCases { | |
setDefaultValue(key) | |
} | |
} | |
} | |
// Iterate through all cases of Keys | |
extension Keys { | |
static var allCases: [Self] { | |
return Mirror(reflecting: self).children.compactMap { $0.value as? Self } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Explicitly using String-based values for Settings