Skip to content

Instantly share code, notes, and snippets.

@BrunoCerberus
Last active July 31, 2023 03:58
Show Gist options
  • Save BrunoCerberus/82428c33855f4ddb4461e10cff3c5d33 to your computer and use it in GitHub Desktop.
Save BrunoCerberus/82428c33855f4ddb4461e10cff3c5d33 to your computer and use it in GitHub Desktop.
Property Wrapper
import Foundation
/// A property wrapper that provides type-safe access to user defaults.
@propertyWrapper
struct UserDefault<Value> {
// MARK: Properties
/// The wrapped value representing the user default.
var wrappedValue: Value {
get {
// Try to get the value for the provided key from UserDefaults.
// If the value is not found or the types don't match, return the default value.
UserDefaults.standard.object(forKey: self.key) as? Value ?? self.defaultValue
}
set {
// Set the value for the provided key in UserDefaults.
UserDefaults.standard.setValue(newValue, forKey: self.key)
}
}
/// The key used to identify the user default in UserDefaults.
let key: String
/// The default value to use when the user default is not set.
let defaultValue: Value
// MARK: Initialization
/// Creates a UserDefault property wrapper with the specified key and default value.
/// - Parameters:
/// - key: The key used to identify the user default in UserDefaults.
/// - defaultValue: The default value to use when the user default is not set.
init(key: String, defaultValue: Value) {
self.key = key
self.defaultValue = defaultValue
}
}
/// A struct containing user default values used in the application.
struct UserDefaultValues {
// MARK: Wrapped Properties
/// A user default representing whether the app introduction has been seen or not.
@UserDefault(key: "hasSeenAppIntroduction", defaultValue: false)
static var hasSeenAppIntroduction: Bool
}
// MARK: Usage
// Setting and retrieving the `hasSeenAppIntroduction` user default value.
UserDefaultValues.hasSeenAppIntroduction = false // Set the value to `false`.
UserDefaultValues.hasSeenAppIntroduction // Retrieve the value, should be `false`.
UserDefaultValues.hasSeenAppIntroduction = true // Set the value to `true`.
UserDefaultValues.hasSeenAppIntroduction // Retrieve the value, should be `true`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment