I'm grinding through Apple's App Development with Swift book and I have been having a few issues with the Optionals sections.
I'm getting stuck accessing a dictionary after I have accessed another dictionary to return an optional value that meets a condition. The error being returned is:
Missing return in a function expected to return 'Double?'
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 priceCheck(name: String) -> Double? {
let pricefinder = name
if let name = stock[name] {
print(name)
if name > 0 {
if let pricefinder = prices[pricefinder] {
print(pricefinder)
return pricefinder
} else {
return nil
}
}
} else {
return nil
}
}
Where am I going wrong with the code above? I need to check if a product is in stock and then return its price if that condition evaluates to true.
And is there a more elegant solution?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…