gpt4 book ai didi

ios - SwiftUI 将 @Published var 从一个 ObservableObject 映射到另一个

转载 作者:行者123 更新时间:2023-12-05 04:59:16 26 4
gpt4 key购买 nike

我希望两个单独的 ObjservableObject 共享一个 @Published 变量。理想情况下像下面这样。由于 Cannot assign to property: '$bar' is immutable 而无法编译。如果对一个或另一个进行更改,我希望 foo 和 bar 保持同步。

class FooState: ObservableObject {
@Published var foo: Bool = false
}

class BarState: ObservableObject {
@Published var bar: Bool

init(fooState: FooState) {
self.$bar = fooState.$foo // compile error
}
}

let fooState = FooState()
let barState = BarState(fooState: fooState)

print(fooState.foo) // false
print(barState.bar) // false

fooState.foo = true
print(fooState.foo) // true
print(barState.bar) // true

最佳答案

目前不支持(我认为)。我知道解决它的唯一方法是自己订阅嵌套的可观察对象并传播 objectWillChange 事件:

class FooState: ObservableObject {
@Published var foo: Bool = false
}

class BarState: ObservableObject {
var fooState: FooState

var bar: Bool {
return self.fooState.foo
}

private var cancellables = Set<AnyCancellable>()

init(fooState: FooState) {
self.fooState = fooState

fooState.objectWillChange
.sink { [weak self] in
self?.objectWillChange.send()
}
.store(in: &cancellables)
}
}

let fooState = FooState()
let barState = BarState(fooState: fooState)

print(fooState.foo) // false
print(barState.bar) // false

fooState.foo = true
print(fooState.foo) // true
print(barState.bar) // true

关于ios - SwiftUI 将 @Published var 从一个 ObservableObject 映射到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63602063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com