Skip to content

Instantly share code, notes, and snippets.

@erdemildiz
Created November 11, 2021 12:48
Show Gist options
  • Save erdemildiz/a63f87311848430ef59cb896b0edf7d5 to your computer and use it in GitHub Desktop.
Save erdemildiz/a63f87311848430ef59cb896b0edf7d5 to your computer and use it in GitHub Desktop.
import Combine
@propertyWrapper
struct UserDefault<Value> {
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 {
// Check whether we're dealing with an optional and remove the object if the new value is nil.
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()
}
}
@erdemildiz
Copy link
Author

Usage

let subscription = UserDefaults.$username.sink { username in
     print("New username: \(username)")
 }
 UserDefaults.username = "Test"
 // Prints: New username: Test 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment