gpt4 book ai didi

swift - 从 Swift 中的函数中的字典返回值

转载 作者:行者123 更新时间:2023-11-28 12:17:04 26 4
gpt4 key购买 nike

我目前正在通过 Apple 的一本 iBooks 快速学习可选内容,但在练习时遇到了一些问题。这些是方向:

Imagine you are creating an app for making purchases. Write a function that will take the name of an item for purchase and will return the cost of that item. In the body of the function, check to see if the item is in stock by accessing it in the dictionary stock. If it is, return the price of the item by accessing it in the dictionary prices. If the item is out of stock, return nil. Call the function and pass in a String that exists in the dictionaries below. Print the return value.

var prices = ["Chips": 2.99, "Donuts": 1.89, "Juice": 3.99, "Apple": 0.50, "Banana": 0.25, "Broccoli": 0.99]
var stock = ["Chips": 4, "Donuts": 0, "Juice": 12, "Apple": 6, "Banana": 6, "Broccoli": 3]

func costOfItem(item: String) -> Double? {
var names = stock.keys
var amount = stock.values

for (names, amount) in stock {
if amount == 0 {
return nil
}
}
}
costOfItem(item: "Chips")

我真的不知道从这里去哪里。在本书中,可选值一直是我非常困惑的单元。我知道我必须返回一个价格,这将是双倍的。我只是不知道如何进入价格字典并推断并返回它。我尝试了一些在线搜索的方法(使用 .contains 方法,比较字符串),但我得到的只是错误。有人可以引导我完成这个练习吗?我真的很想了解这个话题。

最佳答案

你不需要循环。而且您不需要那些第一对 namesamount 变量。只需使用 item 名称获取库存数量。如果不为零,则从 prices 字典中获取成本。

var prices = ["Chips": 2.99, "Donuts": 1.89, "Juice": 3.99, "Apple": 0.50, "Banana": 0.25, "Broccoli": 0.99]
var stock = ["Chips": 4, "Donuts": 0, "Juice": 12, "Apple": 6, "Banana": 6, "Broccoli": 3]

func costOfItem(item: String) -> Double? {
if let available = stock[item] {
if available == 0 {
// none available
return nil
} else {
// return the price
return prices[item]
}
} else {
// unknown item
return nil
}
}

关于swift - 从 Swift 中的函数中的字典返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46106765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com