-5

I am trying to make a checkout screen for an ordering app. I made a struct called dish which has the price as a property. I want to display the total, but I don't know how to total up the prices. I've attempted to use cart.reduce(0, +), but it gives me the error "Ambiguous reference to member '+'".

Any help/advice would be greatly appreciated!

Struct and struct array:

//My struct
struct Dish {
    var price: Double
}

//Struct array
var cart: [Dish] = []

Adding to cart:

//Add an item to cart
    @IBAction func DishTwoOrdered(_ sender: Any) {
        cart.append(Dish(price: 7.50))
        checkoutQuantity.text = "In your cart: \(cart.count)"
    }

Adding indices:

@IBAction func ringUp(_ sender: Any) {
        //Error here
        let sum = cart.reduce(0, +)
        sumLabel.text = "Total: \(sum)"
    }
2
  • 3
    Do not show photos of code! Commented Jan 6, 2021 at 20:28
  • 1
    let sum = cart.reduce(0) { $0 + $1.price } stackoverflow.com/a/49046981/2303865 Commented Jan 6, 2021 at 20:31

1 Answer 1

2

try to use this in 95 line

let sum = cart.reduce(0) { $0 + $1.price }
Sign up to request clarification or add additional context in comments.

8 Comments

I think your answer is better than just closing this as a duplicate. The duplicate question implies that the answer is "just use reduce" but the answer is really "use reduce and provide an expression that adds the current sum with the specific field of your struct."
@DuncanC Yes but his answer was incorrect and he changed after seeing my comment. Anyway I think we can find a better duplicate to add there like this one stackoverflow.com/a/43911758/2303865
Personally I prefer to use map and then reduce, like let sum = cart.map {$0.price}.reduce(0, +) since it lets your reduce statement simplify to (initial_value, operator), but that's personal taste.
@DuncanC you can use map(\.price) in Swift 5.2 or using the extension from my answer sum(\.price)
@LeoDabus I don't see an edit on his answer. How did he change it without leaving an edit entry?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.