alex
alex

Reputation: 154

Why can't I set the value to a @State var without getting this error?

So I have a State var called calmnote that is defined as a string in this struct called calmEdit. I essentially need to set the value of calmNote to the value of content received through an Observable Object called calmManager.

struct calmEdit : View {
@StateObject var CalmManager = calmManager()
@Environment(\.dismiss) var dismiss
@State var calmNote: String = ""

@ViewBuilder
var body: some View {
  
    EmptyView()
    
    ForEach(CalmManager.calmDoccs) { calmDoccs in
    
        self.calmNote = calmDoccs.content  as! String ?? "" // Error: Type '()' cannot conform to 'View'
    
          
      TextEditor(text: $calmNote)
  .padding(.top, 0)
      .padding(.leading, 10)
      .padding(.trailing, 10)
   

    Button( action: {
        CalmManager.updateCalmTheme(calmContent: calmNote, id: idcalm)
    }) {
        Label("Save", systemImage:"") }
    .accentColor(colorScheme == .dark ? Color.pink : Color.pink)
        .padding(10)
    
            }}
 }

Now if I remove the self.calmNote = calmDoccs.content as! String ?? " line i don't get any error, but then again, I won't be able to set the value of the var calmNote to calmDoccs.content. Does anyone know how I can achieve this by not getting this error?

Thanks in advance.

Upvotes: 0

Views: 57

Answers (1)

Darren
Darren

Reputation: 10398

You cannot perform operations like setting a variable from the ViewBuilder like that.

Use the .onAppear or .task modifier to run your code when the view appears.

EmptyView()
    .onAppear {
        self.calmNote = CalmManager.calmDoccs.content as? String ?? ""
    }

Additionally, with this line:

calmDoccs.content  as! String ?? ""

You are forcing it to be a String using ! but saying if it’s not a string use "" which obviously can’t happen.

Upvotes: 1

Related Questions