2

i got the array of dictionary in CartDataModal structure

class CartDataModal: NSObject {
    static let shared_Inst = CartDataModal()
    var cartArrayDict = [[String:Any]]()
}

the received data is in format below

restmenu is after inserting

[
["ItemName": Cheese Burger, "ItemPrice": 50, "ItemQuant": "2"], 
["ItemName": Veg Burger, "ItemPrice": 30, "ItemQuant": 0], 
["ItemName": Chicken Burger, "ItemPrice": 50, "ItemQuant": 0], 
["ItemName": Veg & Crisp Burger, "ItemPrice": 45, "ItemQuant": 0], 
["ItemName": Maharaja Burger, "ItemPrice": 60, "ItemQuant": 0], 
["ItemName": Coke, "ItemPrice": 50, "ItemQuant": 0], 
["ItemName": Pepsi, "ItemPrice": 50, "ItemQuant": 0]
]

how can i count the total number of keyValues for "ItemQuant"?

5
  • You can use cartArrayDict.count for the total number of ItemName, if ItemName are not duplicate. You can add it into set to remove the redundancy. Commented May 22, 2018 at 14:05
  • I'll try those two then inform you guys] Commented May 22, 2018 at 14:12
  • It worked thnx for help Commented May 22, 2018 at 14:19
  • @GurjitSingh, you needed array of ItemNames ? Commented May 22, 2018 at 14:32
  • currently I need total number of "ItemQuant" combined to display it in cart Commented May 23, 2018 at 14:03

2 Answers 2

3

Here is a way to count the number of items in the cartArrayDict while ensuring that only those keys that are "ItemName" are included. It uses the reduce() function of the array with the desired key of the dictionary, with a nil coalescing operator in case the key does not exist.

How to get count of items (by key) in array of dictionaries

let count: Int = cartArrayDict.reduce(0) {
    $0 + ($1["ItemName"] != nil ? 1 : 0)
}
print(count) // Or do whatever you want with the value

How to get total sum of quantities

Here is how to get total sum of the quantities, as asked in comments.

let totalQuantity: Int = cartArrayDict.reduce(0) {
    $0 + ($1["ItemQuant"] as? Int ?? 0)
}
print(totalQuantity) // Or do whatever you want with the value

How to get total price for one type of item

I have presented this as a function.

func getTotalPrice(for name: String) -> Int {
    let totalPrice: Int = cartArrayDict.reduce(0) {
        $0 + ($1["ItemName"] == name ? $1["ItemPrice"] as? Int : 0)
    }
    return totalPrice
}

let totalPriceForCoke = getTotalPrice(for: "Coke")

Note that this assumes the values for key "ItemName" are String type. At present your values are not strings and I am not sure why this should be. I suggest changing it like this: "Coke" instead of Coke.

Sign up to request clarification or add additional context in comments.

13 Comments

but what if I want that for "ItemQuant" to get the quantity for my status bar? its returning 0 for that
@GurjitSingh I have updated answer to make it more generalisable. Just change string "ItemName" to "ItemQuant". Note that this will count the number of elements that have an item quantity, not the total combined quantity. Do you need the total quantity added together?
actually I need total number of quantity to display for number of items in cart
By the way, my code uses the ternary conditional operator and nil coalescing operator, which are very useful. You can find more information here: developer.apple.com/library/content/documentation/Swift/…
@GurjitSingh I thought you would know about it, but I gave more info just in case :)
|
1

You have the array of dictionary:

var cartArrayDict = [[String:Any]]()

You need to map the cartArrayDict to get array of ItemName :

let itemNames: [String] = cartArrayDict.map( { $0["ItemName"] }) as? [String] 

To remove duplicate values just pass it into Set and reconvert into array:

let itemNameArray = Array(Set(itemNames))

In total, You can find out the ItemNameArray as:

    let cartArrayDict = [
        ["ItemName": "Cheese Burger", "ItemPrice": 50, "ItemQuant": "2"],
        ["ItemName": "Veg Burger", "ItemPrice": 30, "ItemQuant": 0],
        ["ItemName": "Chicken Burger", "ItemPrice": 50, "ItemQuant": 0],
        ["ItemName": "Veg & Crisp Burger", "ItemPrice": 45, "ItemQuant": 0],
        ["ItemName": "Coke", "ItemPrice": 60, "ItemQuant": 0],
        ["ItemName": "Coke", "ItemPrice": 50, "ItemQuant": 0],
        ["ItemName": "Pepsi", "ItemPrice": 50, "ItemQuant": 0]
    ]

    if let itemsArr = cartArrayDict.map( { $0["ItemName"] }) as? [String] {
        let itemNameArray = Array(Set(itemsArr))
        print(itemNameArray)
    }

    // Result: ["Veg Burger", "Chicken Burger", "Pepsi", "Cheese Burger", "Coke", "Veg & Crisp Burger"]

3 Comments

Please don't use force unwrap ! in an Swift answer especially to a beginner. Take the time to provide a non-lethal answer. Thanks
@Moritz, I think user wants the total number of ItemName in the line "how can i count the total number of keyValues for "ItemName".
@Moritz, updated the code for force unwrapping ! and converted the Set to Array again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.