Hi I'm trying to learn Swift using Apples Fundamentals of Swift book. There has been a similar post in the past but I have some problems with the answer provided that I would like clarified.
The post was Functions and optionals exercise
I'm on this exercise where you are supposed to print the return value. The return value being either nil if the stock of the item is 0 or the price if the stock is not 0. To add I thought the point was to unwrap the price value if you return it instead of nil. In earlier exercises they had us unwrap the optionals.
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]
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(item: String) -> Double? {
stock[item]! == 0 ? nil : prices[item]
}
print(purchase(item: "Chips"))
If I print(purchases(item: "Chips") I get printed optional(2.99). If it was unwrapped wouldn't it just be 2.99? I could cheat when I call the function and force unwrap but that ruins the point.
When I do try to safely unwrap I get a message saying "Missing return in a function expected to return 'Double?'"
As so:
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(item: String) -> Double? {
if stock[item]! == 0 {
return nil
} else {
if let itemPrice = prices[item] {
return itemPrice
}
}
}
I could add another else return nil after the if let statement but then I'm back to having a wrapped optional.
Thanks for any answers