Dictionaries, Functions and Optionals

1.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 getCost(name: String){
if let item = stock[key]{
    return price[value]
    print("\(value)")
}else {
    return nil
}
}
getCost(name: "Chips")

I am not really sure on how to solve this problem. Here is what I have so far.

From a glance it looks like your function doesn’t have a return type and you’re calling print after a return statement which isn’t allowed.

1 Like

Building on that, you want your function to return a Double?. If you want to run code after a return, a good place to do that is by putting it in a defer block.

1 Like

You also need to make sure that the item is in stock, not only that it's recognised :)

1 Like