SwiftUI update variables in View

Hello everyone, I have this variable:

var total: [Double] {
        var amount: [Double] = []
        for i in 0..<price.count {
            let sum = quantity[i] * price[i]
            amount.append(sum)
        }
        return amount
    }

where its value depends on these two variables

@State var quantity: [Double] = [0.00]
@State var price: [Double] = [0.00]

The user should be able to change the quantity and price of an item in the view, and the variable should update itself automatically.
Unfortunately it doesn’t work and I don’t know why.
Could anyone help me find a solution?
Thank you very much.

Unfortunately it doesn’t work

How doesn’t it work? What do you expect to see happen? What is happening?

You haven’t provided enough information for anyone to help you. Update your question with the SwiftUI code where the person enters the quantity and price and the SwiftUI code that displays the total. You probably need to use the .onChange modifier to calculate the total when the quantity and price change.

One additional question. Why is your total variable an array? Shouldn’t it be a Double that contains the total price of everything the customer ordered?

This topic was automatically closed after 166 days. New replies are no longer allowed.