-4

I’m using Swift playgrounds the “Anwsers Template” Let’s say I have:

Let apple = [“cost”: 10, “nutrition”: 5] Let banana = [“cost”: 15, “nutrition”: 10]

Let choice = askForChoice(Options:[“Apple”, “Banana”])

What is a good, easy way of finding the cost of each fruit, without using a “if” function, because I may make over 100 different things.

John Song
  • 3
  • 3
  • Please copy and paste real code and please format it correctly. – rmaddy Nov 29 '18 at 20:02
  • why don't make a class for fruits (with parameters cost and nutrition) and then make a dictionary of fruits? e.g. make subclasses for apple, banana,.. – ValW Nov 29 '18 at 20:02
  • @rmaddy why do you need the real code? – John Song Nov 29 '18 at 20:11
  • Please include code that you have tried so far. SO is not a code writing service. You should make some effort and then ask when you have a particular problem. – Kamran Nov 29 '18 at 21:04
  • I don’t usually include the entire code because it is very long, and if someone has the promblem they may not understand the answer because it will not apply to their project. But I will include the entire code. – John Song Nov 29 '18 at 21:11

1 Answers1

0
// 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
}
Niv
  • 517
  • 5
  • 18