我正在尝试制作一个类似于 的属性包装器Combine(Published满足我的项目需求),但能够通过向发布者发送存储在 中的值来修改包装的属性projectedValue,如下所示:
// in class
@PublishedMutable var foo = "foo"
$foo.send("bar")
// ...
Run Code Online (Sandbox Code Playgroud)
这是属性包装器的代码:
@propertyWrapper
struct PublishedMutable<Value> {
static subscript<T: ObservableObject>(
_enclosingInstance instance: T,
wrapped wrappedKeyPath: ReferenceWritableKeyPath<T, Value>,
storage storageKeyPath: ReferenceWritableKeyPath<T, Self>
) -> Value {
get {
instance[keyPath: storageKeyPath].storage
}
set {
let publisher = instance.objectWillChange
// This assumption is definitely not safe to make in
// production code, but it's fine for this demo purpose:
(publisher as? ObservableObjectPublisher)?.send()
instance[keyPath: storageKeyPath].storage = …Run Code Online (Sandbox Code Playgroud) swift combine property-wrapper property-wrapper-published swift-property-wrapper