2
votes

I'd like to ask you a question about the usage of mathematical operations inside the view.

struct MyMenu: View {
    var cnt: Int = 0
    let colors: [Color] = [.red, .green, .blue]

    var body: some View {
        ForEach(colors, id: \.self) { color in
            Text(color.description)
                .padding()
                .background(color)

            cnt += 1
        }
    }
}

It gives me an error:

Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols

I do not understand what's wrong with SWIFTUI syntax? Why simple mathematical operations cannot be used inside the some View.

Any solution? Thank you!

2
you cannot "code" in a swiftui -view. maybe you should read some basic tutorials about SwiftUI....just a very view commands are allowed like if then else....Chris

2 Answers

2
votes

You cannot have "regular" code inside you body, as SwiftUI is expecting you to have declarative code to generate the UI in there.

If you would like to increment your cnt property, you need to do it inside a button action for example, like so:

Button(action: {
    cnt += 1
}) {
    Text("Click me to perform any action")
}

Don't forget that your MyMenu object is a struct meaning that by default, it is immutable. You will not be able to update your cnt property if it isn't wrapped with the @State wrapper, or any other depending on your needs :)

Hope this helps! :)

0
votes

If you really need to do it in the SwiftUI Body, you can do it with the .onAppear() Modifier, but as @UIChris pointed out, SwiftUI is expecting to have declarative code to generate just the UI.

Your code would look like that:

struct MyMenu: View {
    var cnt: Int = 0
    let colors: [Color] = [.red, .green, .blue]

    var body: some View {
        ForEach(colors, id: \.self) { color in
            Text(color.description)
                .padding()
                .background(color)
                .onAppear(){
                    cnt += 1
                }
         }
     }
}