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
As a pretty quick solution, all you have to do is to add return nil at the end of your function:
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
}
// here we go:
return nil
}
because at some point (name is not greater than 0), the function does not returns anything.
Also, note that you could implement your function -as a shorter version- as:
func priceCheck(name: String) -> Double? {
let pricefinder = name
if let name = stock[name], name > 0 {
if let pricefinder = prices[pricefinder] {
return pricefinder
}
}
return nil
}
If the function returns nil at the end of it, there is no point of adding else { return nil } for each if; Or you could even use guard statement to achieve it as mentioned in Fogmeister`s answer.