Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Combine Why can't bind data in init?

I am trying a very simple test to just combine a simple Just("JustValue") to a property. But it did not work.
↓ This is my code

struct ResponseView: View {
    
    private var contentCancellable: AnyCancellable? = nil
    @State var content: String = "InitialValue"
    
    var body: some View {
        Text(content)
    }

    init() {
        contentCancellable = Just("JustValue").assign(to: \.content, on: self)
    }
}

Is there anyone know why the Text shows "InitialValue" instead "JustValue"

like image 745
Shaggon Avatar asked Nov 23 '25 22:11

Shaggon


1 Answers

This is specific of state property wrapper initialization pass... the external state storage is created later so only one initialisation is applied.

If you want to update it, do it later, when state be already created and linked to view, like

struct ResponseView: View {
    
    @State var content: String = "InitialValue"
    
    var body: some View {
        Text(content)
            .onAppear {
                _ = Just("JustValue").assign(to: \.content, on: self)
            }
    }
}

the gives UI which you expected.

like image 106
Asperi Avatar answered Nov 26 '25 13:11

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!