Created
November 11, 2021 12:48
-
-
Save erdemildiz/a63f87311848430ef59cb896b0edf7d5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage