标签: swift-property-wrapper

有没有办法访问封闭实例“ObservableObject”以从属性包装器中的任何位置调用“objectWillChange.send()”

我正在尝试制作一个类似于 的属性包装器CombinePublished满足我的项目需求),但能够通过向发布者发送存储在 中的值来修改包装的属性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

7
推荐指数
1
解决办法
828
查看次数