// A good, more object oriented way-
struct Fruit{
var name: String
var cost: Double
var nutrition: Int
}
let fruitsDataHolder = [
Fruit(name: "Apple", cost: 10.0, nutrition: 5),
Fruit(name: "Banana", cost: 15.0, nutrition: 10)
]
func getFruitsCost(fruits: [Fruit]) -> Double{
var totalCost = 0.0
for fruit in fruits{ totalCost += fruit.cost }
return totalCost
}
print(getFruitsCost(fruits: fruitsDataHolder)) // prints 25.0
If you insist on doing that with dictionaries:
let fruitsDataHolder2 = [
["name": "Apple", "cost": 10.0, "nutrition": 5],
["name": "Banana", "cost": 15.0, "nutrition": 10]
]
func getFruitsCost2(fruits: [[String: Any]]) -> Double{
var totalCost = 0.0
for fruit in fruits{
let cost = fruit["cost"] as! Double
totalCost += cost
}
return totalCost
}
print(getFruitsCost2(fruits: fruitsDataHolder2)) // prints 25.0
Edit
Here’s how you can get a specific fruit’s cost based on his name
For the first way-
func getFruitCost(fruitName: String, fruits: [Fruit]) -> Double?{
// searching for the fruit
for fruit in fruits{
if fruit.name == fruitName{
// found the fruit, returning his cost
return fruit.cost
}
}
// couldn't find that fruit
return nil
}
For the second way-
func getFruitCost2(fruitName: String, fruits: [[String: Any]]) -> Double?{
// searching for the fruit
for fruit in fruits{
let currentFruitName = fruit["name"] as! String
if currentFruitName == fruitName{
// found the fruit, returning his cost
return fruit["cost"] as! Double
}
}
// couldn't find that fruit
return nil
}
4
solved How do you find something in a dictionary without knowing the name of the dictionary