Home > Software engineering >  When creating if statement, I get the error type () cannot confirm to View
When creating if statement, I get the error type () cannot confirm to View

Time:03-21

When creating a if statement in swift ui, it shows the error Type () cannot conform to View.

My Code looks like this:

    var body: some View {
        // ************************
         if cookieCounter == 1 {
            cookieCounter = cookieCounter   1
        } 
        // ************************
        ZStack {
            
            
            Color("ColorBlue")
                .ignoresSafeArea()
            
            Spacer()
            
            VStack(spacing: 20) {
                // MARK: - HEADER
                Spacer()
                
                Text("Cookie Clicker Remake")
                    .font(.system(size: 25))
                    .fontWeight(.medium)
                    .foregroundColor(.white)
                    .padding()
                
                Spacer()
                
                Text(String(cookieCounter))
                    .fontWeight(.heavy)
                    .font(.system(size: 50))
                    .multilineTextAlignment(.center)
                    .foregroundColor(.white)
                    
                Spacer()

Im pretty new to Xcode, so I'm not sure what the problem is.

CodePudding user response:

The body of a View is a property that the system uses to generate your UI, it's not a place where you can just run the code that you want. It will also be executed probably a lot more times than you expect, basically every time the system figures out something affecting your view has changed.

If you want to increment your counter, you have to do it when something happens.

Do you want it to happen when the view appears? Then use the .onAppear modifier. Wanna do it on initializer? Then write an init for your View. Want to do it on a button tap? Put it inside the action of a button.

  • Related