您如何在不知道字典名称的情况下在字典中找到某些内容

时间:2018-11-29 19:59:23

标签: swift ipad swift-playground

我正在使用Swift游乐场的“ Anwsers模板” 假设我有:

让苹果= [“成本”:10,“营养”:5] 令香蕉= [“成本”:15,“营养”:10]

让我们选择= askForChoice(选项:[“ Apple”,“ Banana”])

在不使用“ if”功能的情况下,找到每种水果的成本的一种简便好方法是什么,因为我可以制作100多种不同的东西。

1 个答案:

答案 0 :(得分: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

如果您坚持使用字典来做到这一点:

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

修改 这是根据他的名字获取特定水果成本的方法

第一种方式-

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
}

第二种方式-

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
}