简体   繁体   中英

SwiftUI Mathematical operations inside (some View)

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!

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: :)

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
                }
         }
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM