Last active
December 29, 2022 18:39
-
-
Save VladimirBrejcha/0c24c584c2d1a91de2a07cc4f8cacb44 to your computer and use it in GitHub Desktop.
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 | |
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