Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

swift - Functions and optionals exercise

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

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

1 Reply

0 votes
by (71.8m points)

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...