Skip to content

Instantly share code, notes, and snippets.

@VladimirBrejcha
Last active December 29, 2022 18:39
Show Gist options
  • Save VladimirBrejcha/0c24c584c2d1a91de2a07cc4f8cacb44 to your computer and use it in GitHub Desktop.
Save VladimirBrejcha/0c24c584c2d1a91de2a07cc4f8cacb44 to your computer and use it in GitHub Desktop.
import Foundation
fileprivate let userDefaults = UserDefaults.standart
fileprivate let userDefaultsDomain = Bundle.main.bundleIdentifier ?? ""
fileprivate extension String {
var appendingAppDomain: String {
"\(userDefaultsDomain).\(self)"
}
}
@propertyWrapper
struct UserDefault<T> {
let key: String
init(_ key: String) {
self.key = key.appendingAppDomain
}
var wrappedValue: T? {
get { userDefaults.object(forKey: key) as? T }
set { userDefaults.set(newValue, forKey: key) }
}
}
@propertyWrapper
struct NonNilUserDefault<T> {
let key: String
let defaultValue: T
init(_ key: String, defaultValue: T) {
self.key = key.appendingAppDomain
self.defaultValue = defaultValue
userDefaults.register(defaults: [key: defaultValue])
}
var wrappedValue: T {
get { userDefaults.object(forKey: key) as? T ?? defaultValue }
set { userDefaults.set(newValue, forKey: key) }
}
}
// Usage
//
// @UserDefault("storedValue")
// var storedValue: String?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment