user10318011
user10318011

Reputation:

How should I use swift dictionary array to get all value?

My dictionary is like this:

["Coke": ["1", "80"], "Appetizer": ["3", "70"], "Water": ["4", "70"],

"Noodle": ["2", "40"], "Pizza": ["7", "80"],  "Steak": ["7", "60"]]

The value is an array , it includes two values

first number is like how many item you order

second number is like subtotal

I'm just wondering how should I get the second number and save into the new variable ?

because I need to add all number to represent total price

Upvotes: 0

Views: 90

Answers (4)

Rakesha Shastri
Rakesha Shastri

Reputation: 11242

let dict = ["Coke": ["1", "80"], "Appetizer": ["3", "70"], "Water": ["4", "70"], "Noodle": ["2", "40"], "Pizza": ["7", "80"],  "Steak": ["7", "60"]]

Short Answer (directly for your question)

var price = dict.values.reduce(0, { $0 + Double($1[0])! * Double($1[1])! }) // If you need only the price, remove the multiplier
print(price) //1630.0

Long Answer

Like it is always suggested on SO, you should create a data model to hold your information. In this case, it would look something like this,

struct Bill {
    var item: String
    var amount: Int
    var price: Double
}

// For the sake of the example i'll convert your dictionary into Price
var billArray: [Bill] = []
for (key, value) in dict {
    billArray.append(Bill(item: key, amount: Int(value[0]) ?? 0, price: Double(value[1]) ?? 0))
}

// The actual solution that you apply to the price array
var totalBill = billArray.reduce(0, { $0 + Double($1.amount) * $1.price}) // If you need only the price, remove the multipler amount
print(totalBill) //1630.0

Upvotes: 4

Tal Cohen
Tal Cohen

Reputation: 1457

Let's name our dictionary products:

let products = ["Coke": ["1", "80"], "Appetizer": ["3", "70"], "Water": ["4", "70"],
    "Noodle": ["2", "40"], "Pizza": ["7", "80"],  "Steak": ["7", "60"]]    

you can extract the values by using the values methods.

let productValues = products.values

At this point productValues type is [[String]]

the get an array of the second item you can use .map()

let secondItems = productsValues.map { $0[1] }

The last part is a bit tricky because you use string but you can use flatMap and reduce to sum up the values

let result = secondItems.flatMap { Int($0) }.reduce(0, +)

Upvotes: 1

Mihir Mehta
Mihir Mehta

Reputation: 13833

This code should work

let dict:[String:[String]] =  ["Coke": ["1", "80"], "Appetizer": ["3", "70"], "Water": ["4", "70"], "Noodle": ["2", "40"], "Pizza": ["7", "80"],  "Steak": ["7", "60"]]

if let val:String = dict["Coke"]?[1] {
    print(val)
}

Upvotes: 0

Tobias
Tobias

Reputation: 947

You access a dictionary like this:

dict["Coke"]

this will return:

["1", "80"]

if you want to get the second element of the list you simply do the following:

dict["Coke"][1]

Upvotes: 0

Related Questions