How do I display a @Published value?

25 Views Asked by At

I have a Text field in a View that displays the value of an @Published var of an ObservableObject class. I want to update that text whenever the value of that var changes (by user interaction in a different View).

class Scratchpad: ObservableObject {
@Published var contents = "SCRATCHPAD"
}

var scratchpad = Scratchpad()

struct ScratchpadDisplay: View {
var body: some View {  
Text (scratchpad.$contents)
}
}

If I omit the "$", the text displays but doesn't update. With the "$", I get a "Initializer 'init(_:)' requires that 'Published<String>.Publisher' conform to 'StringProtocol'" error. I've stared at it so long I can't see the error!

0

There are 0 best solutions below