在需要@Binding 的地方传递@Published(SwiftUI、Combine)

Pass @Published where @Binding is required (SwiftUI, Combine)

A ViewModel class 有一个 sourceProperty 正在被 TextField 编辑。 属性 就是 @Published。我想将它传递给 Logic class,它有一个带有 Binding<String> 的初始值设定项。 class 将监听 sourceProperty 变化,对它们做出反应并将其输出设置为 @Published output 属性.

如何将 @Published sourceProperty 作为初始化参数传递给 Logic class?

相关代码:

final class ViewModel {
    @Published var sourceProperty: String = ""
    private var logic: Logic?

    init() {
        self.logic = Logic(data: $sourceProperty)
        $logic.output.sink({result in 
            print("got result: \(result)")
        })
    }

}

final class Logic: ObservableObject {
    private var bag = Set<AnyCancellable>()
    @Published var output: String = ""
    @Binding var data: String
    init(data: Binding<String>) {
        self._data = data

        $data.sink({ newValue in 
            output = newvalue + "ABCDE"
        }).store(in: &bag)
    }
}

到目前为止我收到以下错误:

Cannot convert value of type 'Published.Publisher' to expected argument type 'Binding'

目标是使用对象自身的变化 属性 触发另一个对象中的方法调用,然后将第二个对象的输出绑定到某个视图。

视图层:

public struct ViewLayer: View {
    @Binding private var sourceProperty: String

    public init(_ placeholder: String,
                sourceProperty: Binding<String>,
    ) {
        self.placeholder = placeholder
        self._sourceProperty = sourceProperty
    }

    public var body: some View {
        TextField(placeholder, text: $sourceProperty)
    }

 }

如果我正确理解你的问题,你可能正在寻找类似的东西:

final class ViewModel: ObservableObject {
    
    @Published var sourceProperty: String = ""
    private lazy var logic = Logic(data: $sourceProperty)
    private var cancellable: AnyCancellable?

    init() {
        cancellable = logic.$output
            .sink { result in
                print("got result: \(result)")
            }
    }

}

final class Logic: ObservableObject {
    
    @Published private(set) var output: String = ""
    
    init(data: Published<String>.Publisher) {
        data
            .map { [=10=] + "ABCDE" }
            .assign(to: &$output)
    }
}