Skip to content

Instantly share code, notes, and snippets.

@Nirajpaul2
Last active April 15, 2022 04:56
Show Gist options
  • Save Nirajpaul2/533352426733cde612629175b17b2155 to your computer and use it in GitHub Desktop.
Save Nirajpaul2/533352426733cde612629175b17b2155 to your computer and use it in GitHub Desktop.
UserDefaultWrapper
import Foundation
import Combine
@propertyWrapper
struct UserDefaultWrapper<Value: Codable> {
let key: String
let defaultValue: Value
var container: UserDefaults = .standard
private let publisher = PassthroughSubject<Value, Never>()
var wrappedValue: Value {
get {
return container.object(forKey: key) as? Value ?? defaultValue
}
set {
if let optional = newValue as? AnyOptional, optional.isNil {
container.removeObject(forKey: key)
} else {
container.set(newValue, forKey: key)
}
publisher.send(newValue)
}
}
var projectedValue: AnyPublisher<Value, Never> {
return publisher.eraseToAnyPublisher()
}
}
extension UserDefaultWrapper where Value: ExpressibleByNilLiteral {
/// Creates a new User Defaults property wrapper for the given key.
/// - Parameters:
/// - key: The key to use with the user defaults store.
init(key: String, _ container: UserDefaults = .standard) {
self.init(key: key, defaultValue: nil, container: container)
}
}
protocol AnyOptional {
var isNil: Bool { get }
}
extension Optional: AnyOptional {
var isNil: Bool { self == nil }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment