Problem Understanding Variables

I am having trouble wrapping my head around variables. I have read a ton of tutorials but it all seems a little big right now. I made the var myColor and that works just fine. Then when I add line 9 to change the myColor it fails to compile and of course the callout is not much help. I have tried using self.myColor and $myColor and neither seems to work. I think if I could grasp this it would open up a lot of my learning.


import SwiftUI

struct FigureThisOut : View {
    @State var myColor = Color.green

    
        var body: some View {
        
            myColor = Color.red
            Text("reloadCount2").color(myColor)
        
        
    }
}

#if DEBUG
struct FigureThisOut_Previews : PreviewProvider {
    static var previews: some View {
        FigureThisOut()
    }
}
#endif
Answered by m_bedwell in 368859022

In order to hook into the event system, try something like this:


struct ContentView : View {
    @State var myColor = Color.green
    
    
    var body: some View {
        
        VStack {
            HStack {
                Button(action: {self.myColor = Color.red}) {
                    Text("Red")
                }
                Button(action: {self.myColor = Color.green}) {
                    Text("Green")
                }
            }
            Text("Text Color Test").color(myColor)
            }.frame(width: 150, height: 150)
    }
}


That will hook your data change into the event system so you can 'see' the variable change. I'm pretty sure that the View isn't being notified of the data change given that the variable is changed when the view is drawn. Another option would be to write your variable change directly into an event handler such as .onAppear().

add a 'return' statement to line 10. 'some' indicates opaque return types, so the builder has no idea what you are trying to create when you add additional logic to the declaration of the 'body' variable. To avoid the error, you either have to tell it what you actually intend to return from the closure, or, isolate your logic to functions that exist outside of the body variable declaration (and sometimes both if the compiler can't infer what you want to return).


import SwiftUI 

struct FigureThisOut : View { 
    @State var myColor = Color.green 


        var body: some View { 

            myColor = Color.red 
            return Text("reloadCount2").color(myColor) 


    } 
} 

#if DEBUG 
struct FigureThisOut_Previews : PreviewProvider { 
    static var previews: some View { 
        FigureThisOut() 
    } 
} 
#endif

While it does compile now the myColor does not change to red, it stays green.

Do you see the text? Insert a print() statement in that call and see if it's getting hit and not executed, or not getting hit.

Problem Understanding Variables
 
 
Q