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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…