mercredi 16 décembre 2020

How to return a value from an if let statement inside a function?

I am learning Swift by myself from official Apple Curriculum Books, which unfortunately do not come with solutions. I find myself stuck with this problem.

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.

These are the provided dictionaries.

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]

The first part of the problem is quite simple. This is the code I wrote:

func itemInStock(item: String) -> Int? {
    
    if let availableItems = stock[item] {
        switch availableItems {
        case 1...Int.max:
            print("\(item) are available: \(availableItems) items.")
            if let price = prices[item] {
                print("\(item) cost \(price) USD per item.")
                return Int(price)
            }
            
        default:
            print("Sorry, \(item) are out of stock")
            return nil
        }
    
    }
    return Int(price)
}

Without -> Int? and return lines it works fine. When I added return Int(price) and return nil, Xcode gave me an error message: "Missing return in function...".

So I added another return Int(price) line in the end. But Xcode says that it cannot find it in scope.

How can I get that price value from inside if-let statement?

Even if I declare a variable inside the function then set its new value with price inside the switch, it will still have its initial value outside the switch.

It seems that there is a very simple way to handle these situations, but I couldn't find them anywhere. And I tried searching with different keywords.

Aucun commentaire:

Enregistrer un commentaire