Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am new to Swift. Recently, I am working on Swift exercises.

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 purchase(prices:String)->(Int?){
    if stock.index(forKey: prices) == nil{
        return nil
    }else{
        for (String,value) in prices{
            return value
        }
    }
}

I try to access the stock dictionary, but I don't know how to return the result of the given string.

The error is:

type 'String' does not conform to protocol 'Sequence'.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
180 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are doing it totally wrong. I would suggest you to go through the basics first. The requirement can be met as following

func purchase(item:String)->Double?{
    if let price = prices[item] {
        if let quantity = stock[item] { // check for quantitiy of item
            if quantity == 0 { // item present but 0 quantatiy
                return nil
            }
        } else {
            return nil // item not present in stock
        }
        stock[item] = stock[item]! - 1 // one itme sold
        return price // return the price of the item

    } else {
        return nil // item not present in prices
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...